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(request, event_processor, allowed_methods):
11 """Handle an AJAX request"""
12 if not request.method in allowed_methods or not request.is_ajax():
13 # return that the api call failed
14 return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be an ajax request with method ' + str(allowed_methods)}),
15 mimetype="application/json")
17 resp = event_processor(request)
21 return HttpResponse(status=204)
24 def ajax_pk_base(cls, request, pk, event_processor):
25 """Handle an AJAX request"""
26 if not request.is_ajax():
27 # return that the api call failed
28 return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
29 mimetype="application/json")
32 obj = cls.objects.get(pk=pk)
33 event_processor(request.user, obj)
35 except ObjectDoesNotExist:
36 return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'id does not match a ' + cls.__name__}),
37 mimetype="application/json")
39 return HttpResponse(status=204)
42 def ajax_increment(cls, request, pk, field, user_profile_field=None, event_processor=None):
43 def ajax_increment_work(request_user, obj):
44 count = getattr(obj, field)
45 setattr(obj, field, count+1)
49 event_processor(request.user, obj)
51 # Record that user has performed this, to prevent
52 # them from doing it again
53 if user_profile_field:
54 getattr(request_user.get_profile(), user_profile_field).add(obj)
57 return ajax_pk_base(cls, request, pk, ajax_increment_work)