Hi,
I have a ‘weird’ issue with setting initial conditions in a form. I have a list of checkboxs that I would like to pre-select before rendering in HTML. Everything works perfect and as expected as long as I don’t use the order_by clause on my database lookup. I would like the text of the checkboxes labels ( which are names of courses that I get from the database) to be alphabetical. This part does work (showing the text of courses), but the value numbers are no longer sequential in the HTML file. This leads to the problem of being able to select those courses. When I give the form the initial condition to checkbox 1
form = StudentMod(initial={'student':selectedStudent, 'studentCourses':[1]})
it selects the third one not the first. Note that [1] is just for demonstration purposes. I create a list of checkboxes to select based on the courses the student is in.
The value= in the html are in the order that the courses were added to the database and not following the order_by clause. Why is it doing this and how to fix it?
HTML with no order_by clause. Value numbers are sequential.
<label for="id_studentCourses_0"><input type="checkbox" name="studentCourses" value="1" id="id_studentCourses_0" checked>
CHEM1111</label>
</div><div>
<label for="id_studentCourses_1"><input type="checkbox" name="studentCourses" value="2" id="id_studentCourses_1">
CHEM*2400</label>
</div><div>
<label for="id_studentCourses_2"><input type="checkbox" name="studentCourses" value="3" id="id_studentCourses_2">
CHEM3333</label>
</div><div>
<label for="id_studentCourses_3"><input type="checkbox" name="studentCourses" value="4" id="id_studentCourses_3">
CHEM*4444</label>
HTML with order_by clause. Value numbers stay with the course name in the order they are found in the database.
<label for="id_studentCourses_0"><input type="checkbox" name="studentCourses" value="2" id="id_studentCourses_0">
CHEM*2400</label>
</div><div>
<label for="id_studentCourses_1"><input type="checkbox" name="studentCourses" value="4" id="id_studentCourses_1">
CHEM*4444</label>
</div><div>
<label for="id_studentCourses_2"><input type="checkbox" name="studentCourses" value="1" id="id_studentCourses_2" checked>
CHEM1111</label>
</div><div>
<label for="id_studentCourses_3"><input type="checkbox" name="studentCourses" value="3" id="id_studentCourses_3">
CHEM3333</label>
form.py
class StudentMod(forms.Form):
student = forms.ModelChoiceField( queryset=User.objects.filter(groups__name='student'))
studentCourses = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=CourseCode.objects.all().order_by('courseCode'))
Thank you!