ernestophone.ens.fr/propositions/views.py

64 lines
2.2 KiB
Python
Raw Normal View History

2020-01-05 00:32:02 +01:00
from django.shortcuts import redirect, get_object_or_404
2018-01-04 23:33:31 +01:00
from django.urls import reverse_lazy
2015-07-22 22:08:59 +02:00
from django.contrib.auth.decorators import login_required
2020-01-05 17:22:00 +01:00
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db.models import Count, OuterRef, Q, Subquery
2020-01-05 00:32:02 +01:00
from django.views.generic import CreateView, DeleteView, ListView
2015-07-22 22:08:59 +02:00
from django.http import HttpResponseRedirect
2020-01-05 15:58:16 +01:00
from propositions.models import Answer, Proposition
2015-07-22 22:08:59 +02:00
class PropositionCreate(LoginRequiredMixin, CreateView):
template_name = "propositions/create.html"
success_url = reverse_lazy("propositions:list")
2020-01-05 15:58:16 +01:00
model = Proposition
fields = ["name", "artist", "link"]
def form_valid(self, form):
proposition = form.save(commit=False)
proposition.user = self.request.user
proposition.save()
return HttpResponseRedirect(self.success_url)
2015-07-22 22:08:59 +02:00
2020-01-05 00:32:02 +01:00
class PropositionList(LoginRequiredMixin, ListView):
template_name = "propositions/liste.html"
context_object_name = "propositions"
2020-01-05 15:58:16 +01:00
model = Proposition
def get_queryset(self):
user = self.request.user
user_answers = (
Answer.objects
.filter(proposition=OuterRef("id"), user=user)
.values_list("answer", flat=True)
)
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)))
.annotate(user_answer=Subquery(user_answers[:1]))
.order_by("-nb_yes", "nb_no", "name")
)
2020-01-05 17:22:00 +01:00
class PropositionDelete(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
2020-01-05 15:58:16 +01:00
model = Proposition
template_name = "propositions/delete.html"
2020-01-04 00:01:16 +01:00
success_url = reverse_lazy("propositions:list")
2015-07-22 22:08:59 +02:00
2020-01-05 17:22:00 +01:00
def test_func(self):
proposition = self.get_object()
user = self.request.user
return (proposition.user == user or user.profile.is_chef)
2015-07-22 22:08:59 +02:00
2015-07-22 22:08:59 +02:00
@login_required
def answer(request, id, ans):
2020-01-05 15:58:16 +01:00
proposition = get_object_or_404(Proposition, id=id)
2020-01-05 15:30:50 +01:00
user = request.user
Answer.objects.filter(proposition=proposition, user=user).delete()
Answer.objects.create(proposition=proposition, user=user, answer=ans)
2020-01-04 00:01:16 +01:00
return redirect("propositions:list")