208 - Edit course properties - first pass
[oweals/karmaworld.git] / karmaworld / utils / ajax_increment.py
1 import json
2 from django.core.exceptions import ObjectDoesNotExist
3 from django.http import HttpResponseBadRequest, HttpResponseNotFound, HttpResponse
4
5
6 def format_session_increment_field(cls, id, field):
7     return cls.__name__ + '-' + field + '-' + str(id)
8
9
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")
16
17     try:
18         obj = cls.objects.get(pk=pk)
19         event_processor(request.user, obj)
20
21     except ObjectDoesNotExist:
22         return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'id does not match a ' + cls.__name__}),
23                                     mimetype="application/json")
24
25     return HttpResponse(status=204)
26
27
28 def ajax_increment(cls, request, pk, field, event_processor=None):
29     def ajax_increment_work(request_user, obj):
30         count = getattr(obj, field)
31         setattr(obj, field,  count+1)
32         obj.save()
33
34         if event_processor:
35             event_processor(request.user, obj)
36
37         # Record that user has performed this, to prevent
38         # them from doing it again
39         request.session[format_session_increment_field(cls, pk, field)] = True
40
41     return ajax_base(cls, request, pk, ajax_increment_work)