django forms.py和models.py的单选按钮

时间:2014-12-17 04:31:51

标签: python django

您好我尝试在我的表单中创建一个无线电选项,我为此创建了所有相关代码。但该字段不是通过下拉列表或复选框进入无线电选项。我不知道我在做什么错。我在这里给了我的代码。请检查并为此提供一些解决方案。

forms.py

like = forms.TypedChoiceField(choices=BOOL_CHOICES, widget=RadioSelect, coerce=bool)

models.py

 BOOL_CHOICES = ((True, 'male'), (False, 'female'))
 like= models.BooleanField(choices=BOOL_CHOICES)

views.py

 like = product_form.cleaned_data['like'] 

2 个答案:

答案 0 :(得分:0)

以下代码可能有效...已经过测试

 BOOL_CHOICES = ((True, 'male'), (False, 'female'))
 like = forms.ChoiceField(choices=BOOL_CHOICES , widget=forms.RadioSelect())

以下是来自我的申请,并且工作正常..

CHOICES = (('1','Teacher'),('2','Student'))
accountAs =  forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, error_messages={'required':"Please select account type"})

答案 1 :(得分:0)

您需要ChoiceField而不是TypedChoiceField

# forms.py
like = forms.ChoiceField(widget=forms.RadioSelect, choices=BOOL_CHOICES)

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#widgets-inheriting-from-the-select-widget