Django模型字段单选按钮

时间:2016-09-19 06:24:56

标签: django django-models django-templates

如何使用Django模型字段创建单选按钮

#models.py

GENDER_CHOICES = (
   ('M', Male),
   ('F', 'Female')
)

class Profile(models.Model):
     gender = models.CharField(choices=GENDER_CHOICES, max_length=128)

以上字段呈现为选择字段,但我想将其作为  一个单选按钮。

如果问题不正确,有人请更正问题

3 个答案:

答案 0 :(得分:6)

选择字段的默认小部件是选择/选择列表。 你可以在表单中更改小部件

 gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect())

答案 1 :(得分:0)

这适用于Django 2.1及更高版本

models.py保持不变

在admin.py

   from django.contrib import admin 

   class ProfileAdmin(admin.ModelAdmin):

   fields = (......, 'gender',...)

   radio_fields = {'gender': admin.VERTICAL}

答案 2 :(得分:0)

我想你是说enumeration types

from django.utils.translation import gettext_lazy as _

class Student(models.Model):

    class YearInSchool(models.TextChoices):
        FRESHMAN = 'FR', _('Freshman')
        SOPHOMORE = 'SO', _('Sophomore')
        JUNIOR = 'JR', _('Junior')
        SENIOR = 'SR', _('Senior')
        GRADUATE = 'GR', _('Graduate')

    year_in_school = models.CharField(
        max_length=2,
        choices=YearInSchool.choices,
        default=YearInSchool.FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in {
            self.YearInSchool.JUNIOR,
            self.YearInSchool.SENIOR,
        }