我是
django的新手.我正在使用简单的ajax在课程选择的基础上动态更新选择字段学期.但在提交表单时我收到错误选择一个有效的选择.选择的选项不是可用选项之一.代码如下:
forms.py:
from django import forms from Feedback_form.models import course,section_info class loginForm(forms.Form): iquery1 = course.objects.values_list('course_name',flat = True) iquery1_choices = [('','----------')] + [(id,id) for id in iquery1] sem_choices = [('','----------')] course_name = forms.ChoiceField(iquery1_choices,required=True,widget=forms.Select()) semester = forms.ChoiceField(sem_choices,required= True,widget=forms.Select())
views.py:
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(course_id=current_course) no_of_sem = Feedback_form.models.course.objects.values_list('number_of_sem',flat=True).filter(course_id = current_course) no_of_sem = int(no_of_sem[0]) batch_dict = {} for batch in batches: batch_dict[batch.batch_id] = batch.batch_id sem = {} sem[no_of_sem] = no_of_sem data = [batch_dict,no_of_sem] return HttpResponse(json.dumps(data))
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(){ $('#id_course_name').change(function() { request_url = 'login/get_batch/' + c_id + '/'; $.ajax({ url: request_url,success: function(data){ data = $.parseJSON(data); $('#id_semester').html('<option selected="' + "selected" + '">' + '' +'</option>'); for(var i = 1; i<=data[1]; i++) //data[1] contains no of sem $('#id_semester').append('<option value="' + i + '">' + i +'</option>'); },errors: function(e) { alert(e); } }) })
请帮帮我.