且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中使用自定义字段扩展用户模型

更新时间:2023-02-01 10:40:39

最不痛苦,确实是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.