How do I integrate Ajax with Django applications?

前端 未结 8 629
忘了有多久
忘了有多久 2020-11-22 06:16

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have

8条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 06:49

    I am writing this because the accepted answer is pretty old, it needs a refresher.

    So this is how I would integrate Ajax with Django in 2019 :) And lets take a real example of when we would need Ajax :-

    Lets say I have a model with registered usernames and with the help of Ajax I wanna know if a given username exists.

    html:

    Name:

    ajax:

    $('#username_exists_form').on('submit',function(e){
        e.preventDefault();
        var username = $(this).find('input').val();
        $.get('/exists/',
              {'username': username},   
              function(response){ $('#response_msg').text(response.msg); }
        );
    }); 
    

    urls.py:

    from django.contrib import admin
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('exists/', views.username_exists, name='exists'),
    ]
    

    views.py:

    def username_exists(request):
        data = {'msg':''}   
        if request.method == 'GET':
            username = request.GET.get('username').lower()
            exists = Usernames.objects.filter(name=username).exists()
            if exists:
                data['msg'] = username + ' already exists.'
            else:
                data['msg'] = username + ' does not exists.'
        return JsonResponse(data)
    

    Also render_to_response which is deprecated and has been replaced by render and from Django 1.7 onwards instead of HttpResponse we use JsonResponse for ajax response. Because it comes with a JSON encoder, so you don’t need to serialize the data before returning the response object but HttpResponse is not deprecated.

提交回复
热议问题