Reputation: 3
I am trying to make a result management system using django. And for storing the subjects marks, I am using the django inline formset. The problem is that the user have to select a subject manually from dropdown which is Select Field in django and I think this will not be a good choice to do. So I decided to set the SelectField initially to those foreign field. But the initial value is always set to the last object of the Subject model.
def subject_mark_create(request, grade_pk, exam_pk):
subjects = Subject.objects.get_by_grade(grade_pk).order_by('name')
SubjectMarkFormset = inlineformset_factory(Exam, SubjectMark, extra=subjects.count(), max_num=subjects.count(), fk_name='exam', form=SubjectMarkForm, can_delete=False)
exam = get_object_or_404(Exam, pk=exam_pk)
if request.method == "GET":
formset = SubjectMarkFormset(instance=exam)
for form in formset:
for subject in subjects:
form['subject'].initial = subject
What I desired my formset should look like
Upvotes: 0
Views: 872
Reputation: 872
Below code will help you to keep the initial value of subject field of form to a subject object
def subject_mark_create(request, grade_pk, exam_pk):
subjects = Subject.objects.get_by_grade(grade_pk).order_by('name')
SubjectMarkFormset = inlineformset_factory(Exam, SubjectMark, extra=subjects.count(), max_num=subjects.count(), fk_name='exam', form=SubjectMarkForm, can_delete=False)
exam = get_object_or_404(Exam, pk=exam_pk)
if request.method == "GET":
formset = SubjectMarkFormset(instance=exam)
for index, form in enumerate(formset):
form['subject'].initial = subjects[index]
Upvotes: 1