2 from django.core.exceptions import ObjectDoesNotExist
3 from django.http import HttpResponseBadRequest, HttpResponseNotFound, HttpResponse
6 def format_session_increment_field(cls, id, field):
7 return cls.__name__ + '-' + field + '-' + str(id)
10 def ajax_base(cls, request, pk, event_processor):
11 """Handle an AJAX request"""
12 if not (request.method == 'POST' and request.is_ajax()):
13 # return that the api call failed
14 return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
15 mimetype="application/json")
18 obj = cls.objects.get(pk=pk)
19 event_processor(request.user, obj)
21 except ObjectDoesNotExist:
22 return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'id does not match a ' + cls.__name__}),
23 mimetype="application/json")
25 return HttpResponse(status=204)
28 def ajax_increment(cls, request, pk, field, user_profile_field=None, event_processor=None):
29 def ajax_increment_work(request_user, obj):
30 count = getattr(obj, field)
31 setattr(obj, field, count+1)
35 event_processor(request.user, obj)
37 # Record that user has performed this, to prevent
38 # them from doing it again
39 if user_profile_field:
40 getattr(request_user.get_profile(), user_profile_field).add(obj)
43 return ajax_base(cls, request, pk, ajax_increment_work)