Django显示单选按钮的选择

问题描述 投票:0回答:1

我想显示我的用户模型的vaule_fields作为可选择的radiobuttons,任何想法如何做到这一点?

...

template.html

....

目前它们显示为输入字段?!

python django forms
1个回答
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!")

© www.soinside.com 2019 - 2024. All rights reserved.