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.
Another solution is to over-ride the valid_value() method of the ChoiceField. If you are not worried about the possible values the form could return, then it's as simple as this:
class AjaxChoiceField(forms.ChoiceField):
def valid_value(self, value):
return True
Or you could add more validation if needed.
The problem is that ChoiceField
requires the selected option to be in its choice set.
In the above code, the choices for semester
are dynamically updating via jquery. However, these choices are not the part of semester
's choice set i.e. sem_choices
. Hence the problem.
To solve this problem, include the selected value in sem_choices
by using the request.POST
method.
In views.py:
form = loginForm(request.POST)
sem = request.POST.get('semester')
form.fields['semester'].choices = [(sem, sem)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With