Django Models Radio Input

久未见 提交于 2021-02-20 18:58:06

问题


I am trying to incorporate radio buttons in my form. In my forms.py I have the following fields for the form :

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'gender']

In my models.py:

user = models.ForeignKey(User, db_column='user_id')
    first_name = models.CharField(max_length=250)
    last_name = models.CharField(max_length=250
    GENDER = (('M', 'Male'), ('F', 'Female'), ('O', 'Other'))
    gender = models.CharField(max_length=1, choices=GENDER, null=True)

I want gender to be rendered as a radio button not a CharField. But I know the models module do not support the RadioSelect and I cannot use widget either. Is there a way to do this?


回答1:


I don't know why you say you "cannot use widgets either". Of course you can, in the form Meta class:

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'gender']
        widgets = {'gender': forms.RadioInput}


来源:https://stackoverflow.com/questions/41794352/django-models-radio-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!