Hi,
I am working on an UpdateView of a form. I am having hard time
displaying the initial value of grades per subject. I can display the
subjects fine in the template, however I can't display the grades using
the DecimalField. If change DecimalField to ModelChoiceField in
forms.py, I can view the grades in a drop down menu in template but this
is not what I want. I want the user to be able to edit using
DecimalField.
forms.py
class GradeUpdateForm(CrispyFormMixin, forms.ModelForm):
s_name = forms.ModelChoiceField(queryset=Subject.objects.none(), empty_label=None)
final_grade = forms.DecimalField(widget=forms.NumberInput(attrs={'style':'width:80px'}), decimal_places=2, max_digits=5,)
class Meta:
model = SGrade
fields = [
's_name',
'final_grade',
]
I tried playing around with for loop in my views but no good.
views.py
class SchoolDashboardGradesUpdateView(SchoolStudentMixin, UpdateView):
template_name = 'education/dashboard/grades_update.html'
model = SubjectGrade
form_class = GradeUpdateForm
# def get_object(self):
# return get_object_or_404(Recipient, pk=self.kwargs['pk'])
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
form.fields['subject_name'].queryset = Subject.objects.filter(
sgrade__recipient__id=self.kwargs.get('pk'),
sgrade__status='approved').values_list('name', flat=True)
form.fields['final_grade'].queryset = SGrade.objects.filter(
recipient__id=self.kwargs.get('pk'),
status='approved').values_list('final_grade', flat=True)
student = Student.objects.get(id=self.kwargs.get('pk')
for x in student.sgrade_set.all():
if x.status == 'approved':
forms.fields['final_grade'].initial = x.final_grade
for st in student.subjectgrade_set.all():
if st.status == 'approved':
test_dict[
st.subject.name] = st.final_grade
print test_dict
for key, value in test_dict.iteritems():
if key in subject_names:
form.fields['final_grade'].initial = value