Rohini Choudhary
Rohini Choudhary

Reputation: 2473

Not able to update choiceField using jquery in django forms

I am using django Modelform to create form. I want to update my choicefied according to previous choice selected. I am using jquery but below code is not working. Here is my code:

forms.py

from django import forms
from feedback_form.models import course, batch

class loginForm(forms.Form):
    course_name = forms.ModelChoiceField(queryset=course.objects.values_list('course_name', flat = True))
    batch = forms.ModelChoiceField(queryset=batch.objects.none())

class Meta:
    model = batch
    fields = ('course_name', 'batch')

models.py

class course(models.Model):
    course_id = models.CharField(primary_key = True, max_length = 2)
    course_name = models.CharField(max_length = 20)
    stream = models.CharField(max_length = 15)
    number_of_sem = models.IntegerField(max_length = 2)

    def __unicode__(self):
        return self.course_id

    class batch(models.Model):
        batch_id = models.CharField(primary_key = True, max_length = 20)
        course_id = models.ForeignKey(course)
        session = models.IntegerField("Year of the batch", max_length = 10)

        def __unicode__(self):
            return self.batch_id

loginForm.html

<form action="" method="post">
    <table>
        {{ form.as_table }}
    </table>
    {% csrf_token%}
    <input type="submit" value="Submit">
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

   $(document).ready(function(){
   $('select#id_course_name').change(function(){
       c_name = $(this).val();
       request_url = '/get_batch/' + c_name + '/';
       $.ajax({
         url: request_url,
         success: function(data){
            $.each(data[0], function(key, value){
                $('select#id_batch').append('<option value="' + this.key + '">' + this.value +'</option>');
            });  
        }
        return false;
    })
    })
    }); 
 </script>
 </body>

views.py

from django.shortcuts import render, get_object_or_404, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
import json
import feedback_form.models

def get_batch(request, c_id):
current_course = feedback_form.models.course.objects.get(course_name=c_id)
batches = feedback_form.models.batch.objects.all().filter(batch_id=current_course)
batch_dict = {}
for batch in batches:
    batch_dict[batch.id] = batch.batch_id
return HttpResponse(simplejson.dumps(batch_dict), mimetype="application/json")

urls.py

url(r'^get_batch/(?P<c_name>[-\w]+)/$', views.get_batch, name = 'get_batch'),

please help me out.

Upvotes: 1

Views: 1177

Answers (1)

Rohini Choudhary
Rohini Choudhary

Reputation: 2473

Problem is solved. Since here the data received in ajax function for id_batch (or data) is of string type, thatswhy it is not showing any value in choiceField. By adding:

data = $.parseJSON(data);

after

success: function(data){

and removing this pointer form the key and value variable means

$('#id_batch').append('<option value="' + key + '">' + value +'</option>');

solved my problem. For detailed information, check out here. Thanks

Upvotes: 2

Related Questions