Mercurial > public > sg101
annotate contests/views.py @ 629:f4c043cf55ac
Wiki integration. Requests don't always have sessions.
In particular this occurs when a request is made without a trailing slash.
The Common middleware redirects when this happens, and the middleware
process_request() processing stops before a session can get added.
So just set an attribute on the request object for each operation.
This seemed weird to me at first, but there are plenty of examples of this
in the Django code base already.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Tue, 13 Nov 2012 13:50:06 -0600 |
parents | ee87ea74d46b |
children | 89b240fe9297 |
rev | line source |
---|---|
bgneal@540 | 1 """ |
bgneal@540 | 2 Views for the contests application. |
bgneal@540 | 3 |
bgneal@540 | 4 """ |
bgneal@540 | 5 from django.http import (HttpResponse, HttpResponseForbidden, |
bgneal@540 | 6 HttpResponseBadRequest) |
bgneal@540 | 7 from django.shortcuts import get_object_or_404 |
bgneal@540 | 8 from django.utils import simplejson |
bgneal@540 | 9 from django.views.decorators.http import require_POST |
bgneal@540 | 10 |
bgneal@540 | 11 from contests.models import Contest |
bgneal@540 | 12 |
bgneal@540 | 13 |
bgneal@540 | 14 @require_POST |
bgneal@540 | 15 def enter(request): |
bgneal@540 | 16 """ |
bgneal@540 | 17 This view is an AJAX view that is used to enter or withdraw a user from a |
bgneal@540 | 18 given contest. This function toggles the user's entered state in the |
bgneal@540 | 19 contest. |
bgneal@540 | 20 |
bgneal@540 | 21 """ |
bgneal@540 | 22 if not request.user.is_authenticated(): |
bgneal@540 | 23 return HttpResponseForbidden("Please login first") |
bgneal@540 | 24 |
bgneal@540 | 25 contest_id = request.POST.get('contest_id') |
bgneal@540 | 26 if not contest_id: |
bgneal@540 | 27 return HttpResponseBadRequest("Missing contest_id") |
bgneal@540 | 28 |
bgneal@540 | 29 contest = get_object_or_404(Contest, pk=contest_id) |
bgneal@540 | 30 if not contest.can_enter(): |
bgneal@540 | 31 return HttpResponseForbidden("Contest is over") |
bgneal@540 | 32 |
bgneal@540 | 33 # Toggle the user's state in the contest |
bgneal@540 | 34 |
bgneal@540 | 35 result = {} |
bgneal@540 | 36 if request.user in contest.contestants.all(): |
bgneal@540 | 37 contest.contestants.remove(request.user) |
bgneal@540 | 38 result['entered'] = False |
bgneal@540 | 39 result['msg'] = 'You have been withdrawn from this contest.' |
bgneal@540 | 40 else: |
bgneal@540 | 41 contest.contestants.add(request.user) |
bgneal@540 | 42 result['entered'] = True |
bgneal@540 | 43 result['msg'] = 'You have been entered into this contest!' |
bgneal@540 | 44 |
bgneal@540 | 45 json = simplejson.dumps(result) |
bgneal@540 | 46 return HttpResponse(json, content_type='application/json') |