[英]Not able to update choiceField using jquery in django forms
我正在使用Django Modelform创建表单。 我想根据之前选择的选项来更新我的选择。 我正在使用jquery,但以下代码无法正常工作。 这是我的代码:
表格
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'),
请帮帮我。
问题解决了。 由于这里在ajax函数中接收到的id_batch(或数据)数据是字符串类型的,因此为什么在choiceField中不显示任何值。 通过增加:
data = $.parseJSON(data);
后
success: function(data){
并从键和值变量的含义中删除该指针
$('#id_batch').append('<option value="' + key + '">' + value +'</option>');
解决了我的问题。 有关详细信息,请在此处查看 。 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.