Login

Django AJAX Form View

Author:
daveamato
Posted:
August 22, 2016
Language:
Python
Version:
1.7
Tags:
ajax view post
Score:
2 (after 2 ratings)

Django AJAX Form View

A simple example for an AJAX-powered view

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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'})

More like this

Comments

Please login first before commenting.