且构网

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

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

更新时间:2023-02-01 10:23:26

最不痛苦且确实是 Django 推荐的方法是通过 OneToOneField(User) 属性.

The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property.

如果您希望存储与 User 相关的信息,您可以使用 一对一关系到包含附加信息字段的模型.这种一对一模型通常称为配置文件模型,因为它可能存储有关站点用户的非身份验证相关信息.

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 类和/或复制和更改 auth 模块.

I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.