[英]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.