Saturday 21 November 2015

How to apply AJAX in Django forms

 How to apply AJAX in Django forms

This post will help you to apply AJAX in Django forms. Here we will learn to update drop down according to the selection in previous drop down. So lets start.

Scenario: We will generate a form using Django form that will contain two fields Program, Batch. User will first select the Program name from the drop down list. On the basis of selection, the Batch drop down list will be updated.


Step 1. First create Django Form

To create Django form, make a forms.py file inside your Django app.

forms.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django import forms                           # importing Django's forms library
from sample.models import Course, Batch            # import models from app

''' form defination '''
class Update_form(forms.Form):
    '''Query for fetching all available course and provivding them as choices '''
    available_courses = course.objects.values_list('course_name', flat = True)
    course_choices = [('', '----------')] + [(id, id) for id in available_courses]

    batch_choices = [('0', '-----')] #empty batch choice field

    ''' Update_form fields '''
    programme = forms.ChoiceField(course_choices,required=True, widget=forms.Select(attrs={'required':'required'}))
    batch = forms.ChoiceField(batch_choices,required=True, widget=forms.Select(attrs={'required':'required'}))

here sample is the Django app and Course, Batch are model classes.


Step 2. Create a end point in urls.py

Inside your urls.py, add


url(r'^login/login/get_batch/(?P<c_id>\w+)/$', views.get_batch, name = 'get_batch')

Since course id will be like IC, IT hence \w is used in regex part of the url.


Step 3. Apply AJAXin .js file

form.js  


$(document).ready(function(){

          $('#id_programme').change(function(){
            c_id =$(this).val();

            request_url = 'login/get_batch/' + c_id + '/';
            $.ajax({
                url: request_url,
                success: function(data){
                data = $.parseJSON(data);
                //console.log(data);
                $('#id_batch').html('<option selected="' + "selected" + '">' + '' +'</option>');
                $('#id_batch').append('<option value="' + key + '">' + value +'</option>');
                });   

Step 4. Now write view function

Add following in views.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def get_batch(request, c_id):

    '''queries to fetch batch corresponding to current programme selected by user'''
    current_course = feedback_form.models.course.objects.get(course_name=c_id)
    batches = feedback_form.models.batch.objects.all().filter(course_id=current_course)
   
    batch_dict = {}
    for batch in batches:
        batch_dict[batch.batch_id] = batch.batch_id

    data = [batch_dict, no_of_sem]

    return HttpResponse(json.dumps(data))

def update(request):
    if request.method == 'POST' and request.is_ajax:
        form = Update_form(request.POST)
        b = request.POST.get('batch')
        form.fields['batch'].choices = [(b, b)] #to include selected option in batch choice field
       
        if form.is_valid():           
            q = feedback_student_info(batch_id = request.POST['batch'],course = request.POST['programme'])
            q.save()
       else:
            form = loginForm() 

Step 5. Render the form

In template folder of your app where other template files (.html file) is present, add a new .html file.

update.html


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<html>

{% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="" method="post">

        {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>

        <input type="submit" value="Submit" />
    </form> 

</html>

and you are done!

4 comments:

  1. Is there a way to use the above with django model forms?

    ReplyDelete
    Replies
    1. The same procedure will go on, except Django form, you will be using model form.

      Delete
    2. Thank you so much. It helped a lot.:)

      Delete

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel