我想将用户模型的vaule_fields显示为可选择选项单选按钮,知道如何执行此操作吗?
class Send_Payment_Form (forms.ModelForm):
class Meta:
model = User
fields = ['acc_usd_balance', 'acc_eur_balance', 'acc_rub_balance']
CHOICES = (('acc_usd_balance', 'USD',), ('acc_eur_balance', 'EUR',), ('acc_rub_balance', 'RUB',))
choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
template.html
....
<table>
{{ form.as_p }}
{{ field.help_text }}
<br>
</table>
....
当前它们是否显示为输入字段?!
答案 0 :(得分:0)
这是显示为单选按钮的性别选择的示例。
MODELS.PY ********************************************************
#GENDER CHOICES OPTIONS
GENDER_COICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
gender = models.CharField(max_length=3, choices=GENDER_COICES,
default="N/A")
*****************************************************************
FORMS.PY ********************************************************
class UserQForm(UserCreationForm):
""" This is a form used to create a user. """
# Form representation of an image
QUserPictureProfile = forms.ImageField(label="Profile Picture",
allow_empty_file=True, required=False)
password1 = forms.CharField(label="Password", max_length=255,
widget=forms.PasswordInput())
password2 = forms.CharField(label="Confirmation", max_length=255,
widget=forms.PasswordInput())
#GENDER CHOICES OPTIONS
GENDER_COICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
gender = forms.ChoiceField(widget=forms.RadioSelect(), choices=GENDER_COICES)
class Meta:
model = QUser
fields = ('QUserPictureProfile', 'gender',
'email', 'first_name', 'last_name', 'date_of_birth', 'password1',
'password2','phone_number',)
def clean(self):
""" Clean form fields. """
cleaned_data = super(UserQForm, self).clean()
password1 = cleaned_data.get("password1")
password2 = cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords do not match!")