gestiojeux/inventory/views.py

112 lines
3.3 KiB
Python
Raw Normal View History

from django.views.generic import (
TemplateView,
ListView,
DetailView,
RedirectView,
)
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.shortcuts import redirect, get_object_or_404
from django.contrib import messages
from django.http import Http404
from django.core.exceptions import PermissionDenied
from haystack.generic_views import SearchView
from haystack.forms import SearchForm
from haystack.query import SearchQuerySet
from .models import Category, Tag, Game, GameComment
2020-11-22 19:01:21 +01:00
class InventoryView(TemplateView):
template_name = "inventory/inventory.html"
2020-11-22 19:01:21 +01:00
class CategoryListView(ListView):
model = Category
template_name = "inventory/category_list.html"
class CategoryView(DetailView):
model = Category
template_name = "inventory/category.html"
class TagListView(ListView):
model = Tag
template_name = "inventory/tag_list.html"
class TagView(DetailView):
model = Tag
template_name = "inventory/tag.html"
class GameListView(ListView):
model = Game
template_name = "inventory/game_list.html"
class GameView(DetailView):
model = Game
template_name = "inventory/game.html"
class InventorySearchView(SearchView):
form_class = SearchForm
template_name = "inventory/search.html"
def get_queryset(self):
return SearchQuerySet().models(Category, Tag, Game)
class AddGameCommentView(LoginRequiredMixin, SingleObjectMixin, RedirectView):
model = Game
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"]
game = self.get_object()
game.comments.create(author=self.request.user, text=comment_text)
messages.success(self.request, "Commentaire ajouté")
else:
messages.error(
self.request, "Pas de texte pour le commentaire dans la requête"
)
return reverse("inventory:game", kwargs=kwargs)
class ModifyGameCommentView(LoginRequiredMixin, SingleObjectMixin, TemplateView):
model = Game
template_name = "inventory/game.html"
def dispatch(self, *args, **kwargs):
comment_id = kwargs["comment_id"]
self.object = self.get_object()
self.comment = get_object_or_404(GameComment, id=comment_id)
if self.comment.game != 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("inventory:game", slug=kwargs["slug"])
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["edited_comment"] = self.comment
return context