如何在django表单中选择单选按钮?

时间:2018-02-14 05:54:18

标签: django python-3.x forms django-forms

我是表格

class ScoreUpdateForm(forms.Form):
    answer_id = forms.IntegerField()
    given_score = forms.FloatField()
    CHOICES = [('calculated_score', 'Calculated Score'),
               ('given_score', 'Given Score')]

    final_score = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

这是我的模板

 <form action="/teachers/questions/{{ answer.question.id }}/score" method="post">
    {{ form.given_score }}
    {{ form.final_score }}
    <input type="submit" value="Submit"/>
</form>

这是我的观点

def score(request, pk):
        if request.method == 'POST':
            form = ScoreUpdateForm(request.POST)
            if form.is_valid():
                given_score = form.cleaned_data['given_score']
                final_score = form.cleaned_data['final_score']

我可以获得given_score值但不能获得final_score。我想在帖子后的视图中获取所选内容的值。

1 个答案:

答案 0 :(得分:1)

尝试使用

 final_score = form.cleaned_data['final_score']
 final_score = dict(form.fields['final_score'].choices)[final_score]