ernestophone.ens.fr/propositions/views.py
Martin Pépin 5381aba922
Remove the nb_{yes,no} fields
These fields duplicate information that is already present in the Answer
table. I guess they exist(ed) as an optimisation to avoid recomputing
the number of positive and negative answers per proposition each time
the list page is loaded. Given the small number of propositions we have
in practice and the extra housekeeping required to keep these fields up
to date, I consider simplicity matters more here.
2020-01-05 16:34:10 +01:00

66 lines
2.3 KiB
Python

from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Q
from django.views.generic import CreateView, DeleteView, ListView
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from propositions.models import Answer, Proposition
class PropositionCreate(LoginRequiredMixin, CreateView):
template_name = "propositions/create.html"
success_url = reverse_lazy("propositions:list")
model = Proposition
fields = ["name", "artist", "link"]
def form_valid(self, form):
proposition = form.save(commit=False)
proposition.user = self.request.user.profile
proposition.save()
return HttpResponseRedirect(self.success_url)
class PropositionList(LoginRequiredMixin, ListView):
template_name = "propositions/liste.html"
context_object_name = "propositions"
model = Proposition
def get_queryset(self):
return (
Proposition.objects
.annotate(nb_yes=Count("answer", filter=Q(answer__answer=Answer.YES)))
.annotate(nb_no=Count("answer", filter=Q(answer__answer=Answer.NO)))
.order_by("-nb_yes", "nb_no", "name")
)
class PropDelete(DeleteView):
model = Proposition
template_name = "propositions/delete.html"
success_url = reverse_lazy("propositions:list")
@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:list")
else:
self.object.delete()
return HttpResponseRedirect(success_url)
@login_required
def answer(request, id, ans):
proposition = get_object_or_404(Proposition, id=id)
user = request.user
Answer.objects.filter(proposition=proposition, user=user).delete()
Answer.objects.create(proposition=proposition, user=user, answer=ans)
return redirect("propositions:list")