【问题标题】:Django authentication with custom model User使用自定义模型用户进行 Django 身份验证
【发布时间】:2012-05-06 04:25:54
【问题描述】:

对于我的需要,内置模型 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 和所有身份验证功能?

一个好的教程会很棒!

(逐步了解视图、模型和身份验证)

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 这帮我分配了。我朝着正确的方向努力。我唯一忘记的是在我的 UserProfile 模型中添加def is_authenticated(self): return True。见上文
    【解决方案2】:

    我使用了this 文章,它对我来说已经足够好了,希望它对你有用。

    苏丹

    【讨论】:

    • 我刚刚编辑了这个问题。我没有扩展用户。我有自己的用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多