gestiojeux/comments/views.py

60 lines
2.2 KiB
Python
Raw Normal View History

from django.views.generic import TemplateView, RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect, get_object_or_404
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