【问题标题】:Django: Add additional fields to UserCreationFormDjango:向 UserCreationForm 添加附加字段
【发布时间】:2020-11-26 08:31:40
【问题描述】:

我们可以在 django 中向 UserCreationForm 添加其他字段吗?

UserCreationForm默认有5个字段:

  1. 用户名
  2. 电子邮件
  3. 名字
  4. 姓氏
  5. 密码

如果我想添加其他字段,例如年龄、性别,那么如何在 UserCreationForm 中添加这些字段。

我是 django 新手,任何参考或描述性代码都会很明显。

【问题讨论】:

标签: python django django-forms django-users


【解决方案1】:

按照Link 执行此操作

class SignUpForm(UserCreationForm):
    # My Own Custom Fields
    username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))
    first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name')
    last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name')
    email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address')
    password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))
    password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}))

    # The Default Fields Of The UserCreation Form
    class Meta(UserCreationForm.Meta):
        model = User
        # I've tried both of these 'fields' declaration, result is the same
        # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
        fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)

【讨论】:

  • 感谢您的回复,但您提到的字段已经存在于 UserCreationForm 中,我在问一些额外的字段
  • @ShinChan 我写了“我自己的自定义字段”的评论,您可以随时根据需要更改字段。
  • 是的,我同意@AryanMishra。您可以相应地更改字段。
【解决方案2】:

如果您希望存储与用户相关的信息,您可以将 OneToOneField 用于包含字段的模型以获取更多信息。

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    additional_field1 = models.SomeField()
    .....

阅读文档here 了解扩展用户模型的详细信息。

【讨论】:

  • 我应该在哪里写上面的代码,在models.py或forms.py中
  • 在 models.py @ShinChan
猜你喜欢
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 2020-12-10
  • 2014-05-17
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多