首页 > 解决方案 > Django 用户创建表单下拉菜单不显示

问题描述

我有一个从抽象用户子类化的用户类:

models.py

class CustomUser(AbstractUser):

    birth_year = models.PositiveIntegerField(choices=birth_year_choices)
    gender = models.CharField(max_length=1, choices=gender_choices)
    education = models.CharField(max_length=1, choices=education_choices)
    occupation = models.CharField(max_length=1, choices=occupation_choices)
    sector = models.CharField(max_length=1, choices=sector_choices)
    email = models.EmailField(max_length=254, null=True)

    REQUIRED_FIELDS = ['birth_year', 'gender', 'education', 'occupation', 'sector']

以及创建此类用户的注册表单 forms.py

from .models import CustomUser

class SignUpForm(UserCreationForm):
    username = forms.CharField()
    birth_year = forms.IntegerField()
    gender = forms.CharField()
    education = forms.CharField()
    occupation = forms.CharField()
    sector = forms.CharField()
    email = forms.EmailField()

    class Meta:
        model = CustomUser
        fields = ('username', 'birth_year', 'gender', 'education', 'occupation', 'sector','email')

和一个基于类的视图来显示这个 views.py::

class SignUpView(CreateView):
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

我的理解是django应该自动提供一个widget.Select为每个有选择的模型字段,并用下拉菜单呈现表单,但它没有,只有一个文本框。显然,一种解决方案是复制 forms.py 和 models.py 中的选择,但这似乎违反了 django 的 DRY 原则。有更好的解决方案吗?

标签: pythondjangodjango-modelsdrop-down-menudjango-forms

解决方案


推荐阅读