bgneal@540: """ bgneal@540: Views for the contests application. bgneal@540: bgneal@540: """ bgneal@679: import json bgneal@679: bgneal@540: from django.http import (HttpResponse, HttpResponseForbidden, bgneal@540: HttpResponseBadRequest) bgneal@540: from django.shortcuts import get_object_or_404 bgneal@540: from django.views.decorators.http import require_POST bgneal@1085: from django.views.generic import DetailView, ListView bgneal@540: bgneal@540: from contests.models import Contest bgneal@540: bgneal@540: bgneal@1085: class ContestListView(ListView): bgneal@1085: context_object_name = 'contests' bgneal@1085: queryset=Contest.public_objects.all() bgneal@1085: bgneal@1085: def get_context_data(self, **kwargs): bgneal@1085: context = super(ContestListView, self).get_context_data(**kwargs) bgneal@1085: context['V3_DESIGN'] = True bgneal@1085: return context bgneal@1085: bgneal@1085: bgneal@1085: class ContestDetailView(DetailView): bgneal@1085: context_object_name = 'contest' bgneal@1085: queryset=Contest.public_objects.all().prefetch_related('winners') bgneal@1085: bgneal@1085: def get_context_data(self, **kwargs): bgneal@1085: context = super(ContestDetailView, self).get_context_data(**kwargs) bgneal@1085: context['V3_DESIGN'] = True bgneal@1085: return context bgneal@1085: bgneal@1085: bgneal@540: @require_POST bgneal@540: def enter(request): bgneal@540: """ bgneal@540: This view is an AJAX view that is used to enter or withdraw a user from a bgneal@540: given contest. This function toggles the user's entered state in the bgneal@540: contest. bgneal@540: bgneal@540: """ bgneal@540: if not request.user.is_authenticated(): bgneal@540: return HttpResponseForbidden("Please login first") bgneal@540: bgneal@540: contest_id = request.POST.get('contest_id') bgneal@540: if not contest_id: bgneal@540: return HttpResponseBadRequest("Missing contest_id") bgneal@540: bgneal@540: contest = get_object_or_404(Contest, pk=contest_id) bgneal@540: if not contest.can_enter(): bgneal@540: return HttpResponseForbidden("Contest is over") bgneal@540: bgneal@540: # Toggle the user's state in the contest bgneal@540: bgneal@540: result = {} bgneal@540: if request.user in contest.contestants.all(): bgneal@540: contest.contestants.remove(request.user) bgneal@540: result['entered'] = False bgneal@540: result['msg'] = 'You have been withdrawn from this contest.' bgneal@540: else: bgneal@540: contest.contestants.add(request.user) bgneal@540: result['entered'] = True bgneal@540: result['msg'] = 'You have been entered into this contest!' bgneal@540: bgneal@679: json_result = json.dumps(result) bgneal@679: return HttpResponse(json_result, content_type='application/json')