Django:十进制字段初始值

时间:2018-04-23 08:03:22

标签: django foreign-keys form-fields

我正在处理表单的UpdateView。我很难显示每个科目的成绩初始值。我可以在模板中显示主题,但是我无法使用DecimalField显示成绩。如果在forms.py中将DecimalField更改为ModelChoiceField,我可以在模板的下拉菜单中查看成绩,但这不是我想要的。我希望用户能够使用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',
    ]

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

模板

<tbody>
      {% for instance in form.subject_name.field.choices %}
        <tr>
         <td>{{instance.1}}</td>
         <td>{{form.final_grade}}</td>
        </tr>

      {% endfor %}

    </tbody>

有关如何处理此问题的任何建议?我是一个完全的初学者。

0 个答案:

没有答案