steeldonutcollection/frontend/views.py

60 lines
1.8 KiB
Python

from django.views.generic import ListView, DetailView, RedirectView
from django.shortcuts import get_object_or_404
from random import choice
from backend.models import Video, Playlist
class PlaylistView(ListView):
template_name = "frontend/playlist.html"
model = Video
paginate_by = 30
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["title"] = "All Videos"
context["playlists"] = Playlist.objects.all().order_by("title")
context["playlist"] = self.get_playlist()
return context
def get_playlist(self):
if "pk" in self.kwargs.keys():
return get_object_or_404(Playlist, id=self.kwargs["pk"])
def get_queryset(self):
if playlist := self.get_playlist():
queryset = playlist.videos.all()
else:
queryset = Video.objects.all()
queryset = queryset.order_by(self.get_ordering())
return queryset
def get_ordering(self):
ordering = "published" if self.get_playlist() else "-published"
return self.request.GET.get('sort', ordering)
class VideoView(DetailView):
template_name = "frontend/video.html"
model = Video
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["title"] = self.object.title
context["playlist"] = self.get_playlist()
return context
def get_playlist(self):
if (pid := self.request.GET.get("playlist")):
return get_object_or_404(Playlist, id=pid)
class RandomView(RedirectView):
permanent = False
def get_redirect_url(self, *args, **kwargs):
ids = Video.objects.values_list("id", flat=True)
return Video.objects.get(id=choice(ids)).get_absolute_url()