使用自定义模型 User 进行 Django 身份验证

标签 django django-models django-forms django-admin django-views

对于我的需求,内置模型 User 是不够的...所以我有自己的模型 UserProfile,我想通过这个模型在现场进行身份验证(UserProfile 不是从 User 模型继承的,并且与它根本不相关)。

我的模型:

class UserProfile(models.Model):
    password = models.CharField(max_length = 40)
    email = models.EmailField(max_length = 72, unique = True)

    ## Add this so that you can use request.user.is_authenticated
    def is_authenticated(self): 
        return True

但是内置身份验证使用模型用户。

所以我想了解如何更改它,以便身份验证使用我的模型 UserProfile 和所有身份验证功能??

如果有一个好的教程就太好了!

( View 、模型和身份验证的逐步说明)

PS:我知道我可以在其他模型中存储额外的数据,但我不希望这样

最佳答案

这是一个更极端的例子,但说明你想做的事情是可以完成的。作者不仅替换了身份验证后端使用的 User 模型,还使用 ​​SQLAlchemy 代替了 Django ORM。 http://tomforb.es/using-a-custom-sqlalchemy-users-model-with-django

要点是您需要编写后端 authenticateget_user 方法来检索自定义用户模型。如果您还想支持权限,则需要编写 has_perm

关于使用自定义模型 User 进行 Django 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10316460/

相关文章:

python - Django Channels 显示房间中的当前用户

python - Django TemplateView 在错误的地方搜索

python - 如何在 Python 中使用 R 通过 Django 返回一个 R 图?

python - 小写字段值 django 模型查询集

python - Django - 按管理员中的用户配置文件字段排序

python - 使用 PK 而不是用户名的选择字段的 ModelForm

django - 使用 Django 管理站点的多选字段

django - ValueError : not enough values to unpack (expected 2, 得到 1)

python - 如何在具有共享模型和数据库的同一项目中拆分 Django 应用程序的部署?

python - factory_boy 对象似乎缺少主键