Toggle Light / Dark / Auto color theme
Toggle table of contents sidebar
Source code for nkdsu.apps.vote.views.js
from typing import Optional
from django.conf import settings
from django.http import HttpResponse
from django.views.generic import TemplateView
from ..models import Track
from ..templatetags.vote_tags import eligible_for
from ..utils import add_to_list_url , vote_url
[docs]
class JSApiMixin ( object ):
# Yes, it's traversed like HTML, but it's *not* HTML. None of these even
# have <html> elements.
content_type : Optional [ str ] = 'text/plain'
[docs]
def post ( self , request ):
result = self . do_thing ( request . POST )
return HttpResponse ( result , content_type = self . content_type )
[docs]
class SelectionView ( JSApiMixin , TemplateView ):
template_name = 'minitracklist.html'
model = Track
[docs]
def get_queryset ( self ):
return self . model . objects . filter (
pk__in = self . request . session . get ( 'selection' , set ())
)
[docs]
def post ( self , request , * args , ** kwargs ):
self . request = request
self . do_thing ()
context = {}
selection = self . get_queryset ()
context [ 'selection' ] = selection
if len ( selection ) <= settings . MAX_REQUEST_TRACKS :
context [ 'vote_url' ] = vote_url ( selection )
context [ 'add_to_list_url' ] = add_to_list_url ( selection )
return self . render_to_response ( context )
[docs]
class GetSelection ( SelectionView ):
[docs]
def do_thing ( self ) -> None :
pass
[docs]
class Select ( SelectionView ):
[docs]
def do_thing ( self ) -> None :
new_pks : list [ str ] = self . request . POST . getlist ( 'track_pk[]' , [])
selection = set ( self . request . session . get ( 'selection' , []))
for new_pk in new_pks :
if self . request . user . is_authenticated :
base_qs = Track . objects . all ()
else :
base_qs = Track . objects . public ()
qs = base_qs . filter ( pk = new_pk )
if qs . exists ():
track = qs [ 0 ]
if (
self . request . user . is_authenticated and self . request . user . is_staff
) or eligible_for ( track , self . request . user ):
selection . add ( new_pk )
self . request . session [ 'selection' ] = sorted ( selection )
[docs]
class Deselect ( SelectionView ):
[docs]
def do_thing ( self ) -> None :
unwanted_pks : list [ str ] = self . request . POST . getlist ( 'track_pk[]' , [])
selection = set ( self . request . session . get ( 'selection' , []))
for unwanted_pk in unwanted_pks :
if unwanted_pk in selection :
selection . remove ( unwanted_pk )
self . request . session [ 'selection' ] = sorted ( selection )
[docs]
class ClearSelection ( SelectionView ):
[docs]
def do_thing ( self ) -> None :
self . request . session [ 'selection' ] = []