rohini chaudhary rohini chaudhary - 1 year ago 129
Python Question

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:

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')

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


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

<script src=""></script>

c_name = $(this).val();
request_url = '/get_batch/' + c_name + '/';
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;

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.batch_id
return HttpResponse(simplejson.dumps(batch_dict), mimetype="application/json")

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

please help me out.

Answer Source

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);


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download