English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django Ajax Application

Ajax is essentially a combination of technologies integrated together to reduce the number of page loads. We usually use Ajax to mitigate the final user experience. In Django, Ajax can be used directly with Ajax libraries such as jQuery or others. For example, if you want to use jQuery, you need to download and serve the library on a server through Apache or other servers. Then use it in the template, just like developing an Ajax-based application.

Another way to use Ajax in Django is to use Django's Ajax framework. The most commonly used is django-dajax, a powerful tool that can easily represent logic asynchronously and develop web applications super quickly, using Python and almost no JavaScript source code. It supports the four most popular js frameworks: Prototype, jQuery, Dojo, and MooTools

Using Django-dajax

The first thing to do is to install django-dajax. This can be done by using easy_install or pid -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
$ pip install django_dajax
 $ easy_install django_dajax

This will automatically install django-dajaxice, following django-dajaxice is required. Then, we need to configure Ajax and dajaxice.

Add dajax and dajaxice to the INSTALLED_APPS selection in settings.py −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
INSTALLED_APPS += (
    'dajaxice'
    'dajax'
 )

Ensure the following in the same settings.py file −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader'
    'django.template.loaders.app_directories.Loader'
    'django.template.loaders.eggs.Loader'
 )
 TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth'
    'django.core.context_processors.debug'
    'django.core.context_processors.i'18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages'
 )
 STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'dajaxice.finders.DajaxiceFinder',
 )
 DAJAXICE_MEDIA_PREFIX = 'dajaxice'

Now open myapp/Ensure the following settings for dajax URL and loading dajax static js file in url.py file −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
 from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 from django.conf import settings
 Then dajax urls:
 urlpatterns +patterns('',
    url(r'^%s/'% settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),)
 
 urlpatterns +staticfiles_urlpatterns() =

We create a simple table based on the Dreamreal model to store it using Ajax (referring to non-refresh).

Firstly, we need to be in myapp/Dreamreal form in form.py.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
class DreamrealForm(forms.Form):
    website = forms.CharField(max_length = 100)
    name = forms.CharField(max_length = 100)
    phonenumber = forms.CharField(max_length = 50)
    email = forms.CharField(max_length = 100)

Then, we need to be in the application's ajax.py file: myapp/ajax.py. Here is the relevant logic, we save the form and then return the pop-up display result -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from dajaxice.utils import deserialize_form
 from myapp.form import DreamrealForm
 from dajax.core import Dajax
 from myapp.models import Dreamreal
 @dajaxice_register
 def send_form(request, form):
    dajax = Dajax()
    form = DreamrealForm(deserialize_form(form))
    if form.is_valid():
       dajax.remove_css_class('#my_form input', 'error')
       dr = Dreamreal()
       dr.website = form.cleaned_data.get('website')
       dr.name = form.cleaned_data.get('name')}
       dr.phonenumber = form.cleaned_data.get('phonenumber')
       dr.save()
       dajax.alert("Dreamreal Entry %s was successfully saved." % 
          form.cleaned_data.get('name'))
    else:
       dajax.remove_css_class('#my_form input', 'error')
       for error in form.errors:
          dajax.add_css_class('#id_%s' % error, 'error')
 
    return dajax.json()

Now, let's create the dreamreal.html template, which contains the required form -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
    <head></head>
    <body>
       <form action = "" method = "post" id = "my_form" accept-charset = "utf-8">
          {{ form.as_p }}
          <p><input type = "button" value = "Send" onclick = "send_form();"></p>
       </form>
    </body>
 </html>

Supplement, in the template view: myapp/views.py −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
def dreamreal(request):
    form = DreamrealForm()
    return render(request, 'dreamreal.html', locals())

Add the corresponding URL: myapp/urls.py −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),

Now add the necessary code in the template to make Ajax work

Add it at the top of the file -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
{% load static %}
 {% load dajaxice_templatetags %}

Add it in the <head> section of the dreamreal.html template -

We use the JQuery library for this example, so the following code is added

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<script src="{% static/static/jquery-1.11.3.min.js' %}" 
    type="text/javascript" charset="utf-8></script>
 <script src="{% static/static/dajax/jquery.dajax.core.js' %}/script>

Click will call the Ajax function−

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<script>
    function send_form(){
       Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)});
    }
 </script>

Please note that you need to add "jquery-1.11.3.min.js -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
$python manage.py collectstatic

Note - Sometimes jquery.dajax.core.js may be missing, if this happens, just download the source code and place it in the static folder.

Access will show the following screen, /myapp/dreamreal/ −

The following display screen will be displayed after submission −