Advertisement
Guest User

Untitled

a guest
Nov 4th, 2016
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. from django.http import JsonResponse
  2. from django.views.decorators.http import require_POST
  3. @login_required
  4. @require_POST
  5. def image_like(request):
  6.     image_id = request.POST.get('id')
  7.     action = request.POST.get('action')
  8.     if image_id and action:
  9.         try:
  10.             image = Image.objects.get(id=image_id)
  11.             if action == 'like':
  12.                 image.users_like.add(request.user)
  13.             else:
  14.                 image.users_like.remove(request.user)
  15.             return JsonResponse({'status':'ok'})
  16.         except:
  17.             pass
  18.     return JsonResponse({'status':'ko'})
  19.  
  20. We are using two decorators for our view. The login_required decorator
  21. prevents users that are not logged in from accessing this view. The require_GET
  22. decorator returns an HttpResponseNotAllowed object (status code 405 ) if the HTTP
  23. request is not done via GET. This way we only allow GET requests for this view.
  24. Django also provides a require_POST decorator to only allow POST requests and
  25. a require_http_methods decorator to which you can pass a list of allowed methods
  26. as an argument.
  27. In this view we use two GET parameters:
  28. •  image_id : The ID of the image object on which the user is performing
  29. the action
  30. •  action : The action that the user wants to perform, which we assume
  31. to be a string with the value like or unlike
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement