Django:失去理智,用 Django auth 拔掉我的头发

标签 django django-authentication

我正在创建一个 SAAS 作为一个项目,但似乎无法将我的恐龙大脑包裹在这个身份验证系统中。在我意识到你可以添加到正常的身份验证系统之前,我开始推出自己的系统。这是完全错误的吗?我是否应该以某种方式扩展用户模型,但仍然包含我自己的所有属性(用户名、密码等)?

from django.db import models
from django.contrib.auth.models import User
from annoying.fields import AutoOneToOneField
from myproject.core.modelfields import LowerAlphanumericField
from myproject.apps.account.models import Account

class Administrator(models.Model):
    """
    Administrator for an Account (application holds multiple accounts as it is a SAAS).
    """
    account = models.ForeignKey(Account)
    user = AutoOneToOneField(User, primary_key=True)
    name = models.CharField(max_length=255)
    email = models.EmailField()
    username = LowerAlphanumericField(max_length=30)
    password = models.CharField(max_length=255)

如果我访问http://127.0.0.1:8080/admin/auth/user/3/我收到错误,但我创建的第三个管理员对象的主键是 3(假设它是相关用户对象的主键。我是否遗漏了某些内容。另外,我是否需要创建一个密码字段,以及这里都是垃圾,还是我应该这样做?

最佳答案

在我看来,您实际上并不需要添加那么多额外的信息。 Django auth 涵盖了您正在寻找的所有方面:

  • 用户名
  • 密码(sha1 哈希)
  • 名字
  • 姓氏
  • 电子邮件

Django auth 也有一个相当有用的权限系统:

  • super 用户
  • 工作人员
  • 活跃

每当我希望向 User 对象添加附加信息时,我通常会创建一个新模型并存储对 User 的引用。

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    # Extra functionality

然后按照 @bste 的建议,将 AUTH_PROFILE_MODULE = 'accounts.UserProfile' 添加到您的设置文件中。这允许您使用任何 User 对象上的 get_profile() 方法访问用户配置文件(您的额外信息)。

关于Django:失去理智,用 Django auth 拔掉我的头发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2293318/

相关文章:

python - 使用 UserProfile 创建信号时,Django Rest Framework 重复键值违反唯一约束

python - 如何使用 Django 和 Python 迁移现有表

javascript - 属性错误: 'NoneType' object has no attribute 'is_active'

android - 如何在我的 Android 应用程序中使用 django 身份验证(django.contrib.auth)

Django使用匿名用户保存模型

python - Django UserProfile ...没有密码

python - Django 错误 : relation "users_user" does not exist

python - Django注册: Redirect after registering fails because of missing argument

django - Django 中的 SlugField 有什么用?

Django 自定义后端 : Cannot Login when using custom backend for authentication with email