Monday, March 3, 2014

Setup JQuery and Ajax on Django Framework

This based on my experience using JQuery Ajax on Django Framework, the first thing and basic thing to do setup JQuery on Django is about static file.

What is static file ?
Let say static file is file that never changed when page is loading, if you already familiar with web programming you should know about .css, .js , image file, .html file. And then let say those file is static file :-).

How to setup static file on Django ?
# Create static folder under your Django project, place it in same directory as manage.py



# Setup settings.py and add some definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles'
)
 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.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.csrf',
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

)
# Place your JQuery file in to static folder, in this case I will place it in static/assets/js/jquery/jquery-1.11.0.min.js. Need to install JQuery Cookie from https://github.com/carhartl/jquery-cookie

# Setup your template file, and load static JQuery file from there. If you are not familiar with DJango template concept you can refer to https://docs.djangoproject.com/en/1.6/intro/tutorial01/ I think template section in tutorial06. Just feel free to explore on Django documentation and tutorial.
Load static JQuery from your template, this is sample from mine.
{% load static %}
<html>
  <head>
    <title>Join Entrophy</title>
    <link rel="stylesheet" type="text/css" href="{% static "assets/css/base.css" %}">
    <script src="{% static "assets/js/jquery/jquery-1.11.0.min.js" %}"></script>
    <script src="{% static "assets/js/jquery-cookie/jquery.cookie.js" %}"></script>
    <script src="{% static "assets/js/users.js" %}"></script>

    <script>
      $(document).ready(function() {
        users_instance.init ();
        users_instance.base_url = "{{ base_url }}";
      });
    </script>
  </head>
  <body>
    <div id="register_wait" class="login_form"><div class="wait_indicator">Loading...</div></div>
    <div id="register_form" class="login_form">
      <div id="register_msg" class="error_msg"></div>
      <div><input id="reg_user_email" type="text" name="user_email" placeholder="Email"></div>
      <div><input id="reg_user_firstname" type="text" name="user_firstname" placeholder="First Name"></div>
      <div><input id="reg_user_lastname" type="text" name="user_lastname" placeholder="Last Name"></div>
      <div><input id="reg_user_password" type="password" name="user_password" placeholder="Password"></div>
      <div><input id="reg_user_repassword" type="password" name="user_repassword" placeholder="Re Type Password"></div>
      <div><button id="reg_user_join">Join</button></div>
    </div>
  </body>
</html>
# After this step we can call JQuery Ajax code snippet using, $.ajax ()
 $.ajax ({
    type:"POST",
    url:"",
    data:
    {
    },
    success:function (data)
    {
    },
    error:function ()
    {
    }
});
Of course those ajax code snippet will work, but there is little thing you need to know, which is Django will give output 404 forbidden :-). Because Django care about security abuse csrf, you can read my article about csrf here http://xyzmind.blogspot.com/2014/02/cross-site-request-forgery-protection.html.

How to setup csrf token, to make Django give corect output ?

# Open settings.py and add this section in to it
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.csrf',
)


MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)

# Import csrf module on views.py
from django.core.context_processors import csrf
from django.views.decorators.csrf import ensure_csrf_cookie
# Add @ensure_csrf_cookie to your function that will called by Ajax
@ensure_csrf_cookie
def register (request):
    c = {} # csrf request
    c.update (csrf (request)) # csrf request

    context = {'base_url':request.get_host ()}
    context = dict (list (context.items ()) + list (c.items ()))
    # call your template page, you can validate with jquery cookie
    return render (request, 'register.html', context)
# Before you call using $.Ajax jquery you need to setup ajax setup JQuery and change the header information with crfs token
$.ajaxSetup({
    crossDomain: false,
    beforeSend: function (xhr, settings)
    {
        if (!users_instance.csrfSafeMethod (settings.type))
        {
            xhr.setRequestHeader ("X-CSRFToken", $.cookie ('csrftoken'));
        }
    }
});
$.cookie is JQuery plugin, need to install manual from https://github.com/carhartl/jquery-cookie

That the way :-)

22 comments:

  1. I must be thankful for sharing your ideas.Thank you for the good writeup.its a brellint job.please visit here for more detail:
    Packers and Movers Delhi
    http://packers-and-movers-delhi.in/packers-and-movers-dwarka-delhi
    http://packers-and-movers-delhi.in/packers-and-movers-gurgaon
    Packers and Movers Noida

    ReplyDelete
  2. Every Indian woman wants all Eyes to be on her at weddings, festivals,
    and other traditional get-togethers. Now that is a lot of hard work, isn't it?
    Stylizone now helps you be at your fabulous
    ethnic wear best with its collection of fine lehengas in India.
    Plz visit:- Lahenga

    ReplyDelete



  3. Designer Kurtis is perhaps the desire of every single girl in this world to look amazing on her day.
    It is certainly important that the bride must be the star of the show.The most beautiful woman at the venue.
    In India,Designer Kurtis are the most obvious choice for the brides.There are many designer Kurtis in our site...
    For more...
    Plz visit:- Designer Kurtis

    ReplyDelete
  4. Designer Salwer Suit is perhaps the desire of every single girl in this world to look amazing on her wedding day.
    It is certainly important that the bride must be the star of the show.The most beautiful woman at the wedding venue.
    In India,Salwer Suit are the most obvious choice for the brides.There are many Salwer Suit in our site...
    For more...
    Plz visit:- Salwer Suit

    ReplyDelete
  5. You can wear this Punjabi Suit with silver earrings, gold earrings, an American diamond pendant or stone studded jewelry. You can buy Patiala salwar kameez online at Stylizone. Select from the widest collection Patiala salwar suits and get an exquisite design for you. There is something for everyone here. We even offer customized tailoring.
    For more.... Please visit Punjanbi Suit

    ReplyDelete
  6. Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog.
    here
    here

    ReplyDelete
  7. Packers and movers in Delhi - We give vast importance to loading and unloading, because it is at this stage that damage to goods frequently occurs.

    ReplyDelete
  8. Delhi Escorts are truly gorgeous in their appearance and have some of the stunning characteristics inside them to enthrall their customers. Whatever you would want from our darlings, they are each time being ready to flaunt their ideas.

    $$ defence colony call girls
    $$ east of kailash call girls
    $$ hauz khas call girls
    $$ pitampura call girls
    $$ patel nagar call girls
    $$ model town call girls
    $$ chandni chowk call girls
    $$ gtb nagar call girls
    $$ Russian Call Girls Delhi

    ReplyDelete
  9. Call/Whatsapp+91- 9873777170 Delhi Escorts service & Delhi Erotic girls | Colege call girls service facility available. visit my blog:-
    Daryaganj Escorts &&
    Defence Colony Escorts &&
    Delhi Cantt Escorts &&
    Dhaula Kuan Escorts &&
    Nehru Place Escorts &&
    Malviya Nagar Escorts &&
    Saket Escorts &&

    ReplyDelete