我有一个带整数字段的模型类(= scored_place_number)。
我希望用户为我将表单字段设置为
的字段选择1,2或3forms.MultipleChoiceField # set it to IntegerField
表格。
表单显示正常但是当通过点击提交按钮提交表单时,django会显示错误。
Enter a list of values
当我确实指定了forms.MultipleChoiceField时它赢了,这样我就猜错了将整数字段和MultipleChoiceField组合起来是错误的。
如何使用form.MultipleChoiceField for Model的IntegerField?
模型
class ComparisonScore(models.Model):
comparison = models.ForeignKey(Comparison, on_delete=models.CASCADE, null=True)
first_place = models.ForeignKey(Place, related_name="scored_place", on_delete=models.CASCADE, null=True)
second_place = models.ForeignKey(Place, related_name="unscored_place", on_delete=models.CASCADE, null=True)
scored_place_number = models.IntegerField(null=True)
表格
class ComparisonScoreForm(forms.ModelForm):
class Meta:
model = ComparisonScore
fields = '__all__'
scored_place_number = forms.MultipleChoiceField(
required=True,
widget=forms.RadioSelect,
choices=(
('neither', 0),
('first_place', 1),
('second_place', 2)
)
)
查看
class CreateComparisonScoreView(CreateView):
model = ComparisonScore
form_class = ComparisonScoreForm
success_url = reverse_lazy('comparison:index')
答案 0 :(得分:1)
将元组中的第一项重新定义为整数,这些是定义字段类型的第一项:
scored_place_number = forms.ChoiceField(
required=True,
widget=forms.RadioSelect,
choices=(
(0,'neither',),
(1,'first_place'),
(2,'second_place')
)
)