【问题标题】:Data being stored in User class instead of UserProfile数据存储在 User 类而不是 UserProfile
【发布时间】:2016-03-06 23:12:34
【问题描述】:

我正在尝试创建一个使用默认身份验证的自定义类Employee。我能够成功注册,但与 Django 的用户类关联的字段存储在 User 中,而我的自定义字段存储在 Employee 中。如何获取存储在 Employee 中的所有内容?

这是我的forms.py

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password')

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = ('sales', 'hours')

还有我的models.py

class Patient(models.Model):
    user = models.OneToOneField(User)
    sales = models.CharField(max_length=30)
    hours = models.CharField(max_length=30)

就像我说的,我更喜欢使用默认身份验证,因此避免使用自定义后端

【问题讨论】:

标签: django django-models django-forms django-admin


【解决方案1】:

您使用的通常称为用户配置文件,它不会将添加的字段存储在同一个表中(您已经发现)。更多信息可以在Extending existing user model找到。

您想要做的(以及我在项目中通常需要使用的方法)是Substitute a custom user model。它有点复杂,但是一旦你掌握了它,它就不会太糟糕了。它将允许您将所有用户字段存储在一个表中,而不是单独的表/模型中。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2021-01-25
    • 2016-10-11
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2015-07-05
    相关资源
    最近更新 更多