I am newbie in django. I am using simple ajax to dynamically update the choice field semester on the basis of course selection. But while submitting the form i am getting the error Select a valid choice. selected option is not one of the available choices. Code is as follow:
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);
}
})
})
Please help me out.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…