如何在基于UserCreationForm的类中添加选择字段?

时间:2019-04-19 07:40:40

标签: django

我有一个问题,我如何在类UserCreationForm中添加ChoiceField。我试图添加,但是问题是“要解压缩的值太多(预期2)”,我不知道为什么。我有下面的代码。感谢您的帮助

我的模型。py

class Viewer(models.Model):
    INTERESTS_CHOICES = (
        ('IT', 'IT'),
        ('MARKETING', 'marketing'),
        ('BUISINESS', 'buisiness'),
        ('DESIGN', 'design'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    interests = models.CharField(choices=INTERESTS_CHOICES, max_length=8, default='IT')
    def __str__(self):
        return self.user.username

我的表格.py

INTERESTS_CHOICES = (
        ('IT', 'IT'),
        ('MARKETING', 'marketing'),
        ('BUISINESS', 'buisiness'),
        ('DESIGN', 'design'),
    )
class ViewerRegisterForm(UserCreationForm):

    email = forms.EmailField(required=False)
    interests = forms.ChoiceField(choices=[INTERESTS_CHOICES])
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_viewer = True
        user.save()
        viewer = Viewer.objects.create(user=user)
        return user

1 个答案:

答案 0 :(得分:0)

尝试删除选项附近的列表括号,也许forms.Select会更好?

class ViewerRegisterForm(UserCreationForm):
    fields = ['username', 'interests', 'email', 'password1', 'password2']

widgets = {
    interests = forms.Select(choices=INTERESTS_CHOICES)}