在Django中使用自定义字段扩展用户模型 [英] Extending the User model with custom fields in Django
问题描述
使用自定义字段扩展用户模型(与Django认证应用程序捆绑在一起)的最佳方式是什么?我也可能希望使用电子邮件作为用户名(用于身份验证)。
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).
我已经看到一个几个 方式来做,但不能决定哪一个是最好的。 / p>
I've already seen a few ways to do it, but can't decide on which one is the best.
推荐答案
最不痛苦,确实是Django推荐的方法是通过一个 OneToOneField(User)
属性。
The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User)
property.
扩展现有的用户模型
…
Extending the existing User model
…
如果您想存储与用户
相关的信息,可以使用一对一关系到包含附加信息字段的模型。这种一对一模型通常称为配置文件模型,因为它可能存储有关站点用户的非验证相关信息。
If you wish to store information related to User
, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.
那就是说,扩展 django.contrib.auth.models.User
并取代它也可以工作...
That said, extending django.contrib.auth.models.User
and supplanting it also works...
替换自定义用户模型
某些项目可能具有Django内置的认证要求
User
模型并不总是适合的。例如,在某些网站上,使用电子邮件地址作为识别令牌而不是用户名更有意义。
Substituting a custom User model
Some kinds of projects may have authentication requirements for which Django’s built-in
User
model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.
[Ed:两个警告和之间的通知,请注意这是非常激烈的。]
[Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]
我绝对不要在Django源代码树中更改实际的User类,或者复制和更改验证模块。
I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.
这篇关于在Django中使用自定义字段扩展用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!