Django用户创建表单下拉列表不显示

2024-05-13 21:58:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户类,它是抽象用户的子类:

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应该自动提供一个小部件。为每个有选择的模型字段选择,并使用下拉菜单呈现表单,但它没有,只有一个文本框。显然,一种解决方案是复制forms.py和models.py中的选项,但这似乎违反了django的DRY原则。有更好的解决办法吗


Tags: 用户pymodelsformsgenderyearlengthmax