我有一个用户类,它是抽象用户的子类:
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原则。有更好的解决方案吗?