Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.http import JsonResponse
- from django.views.decorators.http import require_POST
- @login_required
- @require_POST
- def image_like(request):
- image_id = request.POST.get('id')
- action = request.POST.get('action')
- if image_id and action:
- try:
- image = Image.objects.get(id=image_id)
- if action == 'like':
- image.users_like.add(request.user)
- else:
- image.users_like.remove(request.user)
- return JsonResponse({'status':'ok'})
- except:
- pass
- return JsonResponse({'status':'ko'})
- We are using two decorators for our view. The login_required decorator
- prevents users that are not logged in from accessing this view. The require_GET
- decorator returns an HttpResponseNotAllowed object (status code 405 ) if the HTTP
- request is not done via GET. This way we only allow GET requests for this view.
- Django also provides a require_POST decorator to only allow POST requests and
- a require_http_methods decorator to which you can pass a list of allowed methods
- as an argument.
- In this view we use two GET parameters:
- • image_id : The ID of the image object on which the user is performing
- the action
- • action : The action that the user wants to perform, which we assume
- to be a string with the value like or unlike
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement