extensions-website/ratings/views.py

74 lines
2.4 KiB
Python

import logging
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from ratings.models import Rating
import extensions.views.mixins
log = logging.getLogger(__name__)
class RatingsView(extensions.views.mixins.ListedExtensionMixin, ListView):
model = Rating
paginate_by = 15
queryset = Rating.objects.listed
def _set_score_filter(self):
score = None
if 'score' in self.request.GET:
try:
score = int(self.request.GET['score'])
self.score = next(
(score for _score in Rating.SCORES.values if score == _score),
None,
)
except Exception:
pass
self.score = score
def get_queryset(self):
self._set_score_filter()
queryset = super().get_queryset().filter(extension_id=self.extension.pk)
if self.score:
queryset = queryset.filter(score=self.score)
return queryset.distinct()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['extension'] = self.extension
context['score'] = self.score
if self.request.user.is_authenticated:
context['my_rating'] = Rating.get_for(self.request.user.pk, self.extension.pk)
return context
class AddRatingView(
extensions.views.mixins.ListedExtensionMixin,
UserPassesTestMixin,
LoginRequiredMixin,
CreateView,
):
model = Rating
fields = ('score', 'text')
def test_func(self) -> bool:
# FIXME: best to display a friendly message instead of just responding with a 403
# TODO: E.g: "you already rated this extension" or "cannot rate your own extension"
return self.extension.can_rate(self.request.user)
def form_valid(self, form):
"""Link newly created rating to latest version and current user."""
form.instance.version = self.extension.latest_version
form.instance.user = self.request.user
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['extension'] = self.extension
return context
def get_success_url(self) -> str:
return self.extension.get_ratings_url()