在 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).
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.
…
如果您希望存储与 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.
这篇关于在 Django 中使用自定义字段扩展用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!