comparison gpp/contests/views.py @ 540:51fa1e0ca218

For #243, create a contests application.
author Brian Neal <bgneal@gmail.com>
date Mon, 09 Jan 2012 01:13:08 +0000
parents
children
comparison
equal deleted inserted replaced
539:2f0a372c92b4 540:51fa1e0ca218
1 """
2 Views for the contests application.
3
4 """
5 from django.http import (HttpResponse, HttpResponseForbidden,
6 HttpResponseBadRequest)
7 from django.shortcuts import get_object_or_404
8 from django.utils import simplejson
9 from django.views.decorators.http import require_POST
10
11 from contests.models import Contest
12
13
14 @require_POST
15 def enter(request):
16 """
17 This view is an AJAX view that is used to enter or withdraw a user from a
18 given contest. This function toggles the user's entered state in the
19 contest.
20
21 """
22 if not request.user.is_authenticated():
23 return HttpResponseForbidden("Please login first")
24
25 contest_id = request.POST.get('contest_id')
26 if not contest_id:
27 return HttpResponseBadRequest("Missing contest_id")
28
29 contest = get_object_or_404(Contest, pk=contest_id)
30 if not contest.can_enter():
31 return HttpResponseForbidden("Contest is over")
32
33 # Toggle the user's state in the contest
34
35 result = {}
36 if request.user in contest.contestants.all():
37 contest.contestants.remove(request.user)
38 result['entered'] = False
39 result['msg'] = 'You have been withdrawn from this contest.'
40 else:
41 contest.contestants.add(request.user)
42 result['entered'] = True
43 result['msg'] = 'You have been entered into this contest!'
44
45 json = simplejson.dumps(result)
46 return HttpResponse(json, content_type='application/json')