from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.views.generic import DeleteView from django.utils.decorators import method_decorator from django.http import HttpResponseRedirect from propositions.forms import PropForm from propositions.models import Prop from propositions.models import Reponses @login_required def create_prop(request): if request.method == "POST": form = PropForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.nboui = 0 obj.nbnon = 0 obj.user = request.user.profile obj.save() envoi = True else: form = PropForm() return render(request, "propositions/create.html", locals()) @login_required def liste(request): props = Prop.objects.all().order_by('-nboui', 'nbnon', 'nom') n = len(props) return render(request, 'propositions/liste.html', locals()) @login_required def repoui(request, id): prop = get_object_or_404(Prop, id=id) participant = request.user.profile try: p = Reponses.objects.get(prop=prop, part=participant) if p.reponse == "oui": prop.nboui -= 1 else: prop.nbnon -= 1 p.delete() except Reponses.DoesNotExist: pass rep = Reponses() rep.prop = prop rep.part = participant rep.reponse = "oui" rep.save() prop.nboui += 1 prop.save() return redirect('propositions.views.liste') class PropDelete(DeleteView): model = Prop template_name = "propositions/delete.html" success_url = reverse_lazy(liste) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(PropDelete, self).dispatch(*args, **kwargs) def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() if not ((self.object.user == self.request.user.profile) or self.request.user.profile.is_chef): return redirect('propositions.views.liste') else: self.object.delete() return HttpResponseRedirect(success_url) @login_required def test(request, pk): error = "Connard" if True: return redirect(PropDelete.as_view()) return render(request, "propositions/liste.html", locals()) @login_required def repnon(request, id): prop = get_object_or_404(Prop, id=id) participant = request.user.profile try: p = Reponses.objects.get(prop=prop, part=participant) if p.reponse == "oui": prop.nboui -= 1 else: prop.nbnon -= 1 p.delete() except Reponses.DoesNotExist: pass rep = Reponses() rep.prop = prop rep.part = participant rep.reponse = "non" rep.save() prop.nbnon += 1 prop.save() return redirect('propositions.views.liste')