bgneal@540: """ bgneal@540: Views for the contests application. bgneal@540: bgneal@540: """ 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.utils import simplejson bgneal@540: from django.views.decorators.http import require_POST bgneal@540: bgneal@540: from contests.models import Contest bgneal@540: bgneal@540: 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@540: json = simplejson.dumps(result) bgneal@540: return HttpResponse(json, content_type='application/json')