gestiojeux/comments/views.py
sinavir c01ed7cb47 style(pre-commit): Add hook
Python:
- black
- isort (black profile)
- ruff

Nix:
- statix
- nixfmt-rfc-style
- deadnix
2024-07-04 20:47:46 +02:00

59 lines
2.2 KiB
Python

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import RedirectView, TemplateView
from django.views.generic.detail import SingleObjectMixin
class AddCommentView(LoginRequiredMixin, SingleObjectMixin, RedirectView):
permanent = False
def get_redirect_url(self, *args, **kwargs):
req_dict = self.request.POST
if "comment_text" in req_dict:
comment_text = req_dict["comment_text"]
comment = self.comment_model(
commented_object=self.get_object(),
author=self.request.user,
text=comment_text,
)
comment.save()
messages.success(self.request, "Commentaire ajouté")
else:
messages.error(
self.request, "Pas de texte pour le commentaire dans la requête"
)
return super().get_redirect_url(*args, **kwargs)
class ModifyCommentView(LoginRequiredMixin, SingleObjectMixin, TemplateView):
def dispatch(self, *args, **kwargs):
comment_id = kwargs.pop("comment_id")
self.object = self.get_object()
self.comment = get_object_or_404(self.comment_model, id=comment_id)
if self.comment.commented_object != self.object:
raise Http404()
if self.comment.author != self.request.user:
raise PermissionDenied()
return super().dispatch(*args, **kwargs)
def post(self, *args, **kwargs):
req_dict = self.request.POST
if "comment_text" in req_dict:
self.comment.text = req_dict["comment_text"]
self.comment.save()
messages.success(self.request, "Commentaire modifié")
else:
messages.error(
self.request, "Pas de texte pour le commentaire dans la requête"
)
return redirect(self.success_pattern_name, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["edited_comment"] = self.comment
return context