首页 > 解决方案 > 超级用户与普通用户的不同模型字段要求?django

问题描述

示例(不是真实示例):我希望超级用户在注册他们的用户名和电子邮件时必须保存。和普通用户保存用户名、电子邮件和数字(唯一=真)。

我想使用 django 拥有的用户模型,但我不知道数字何时必须是唯一的?或者更确切地说,我最初希望它是主键,但仅适用于普通用户。我是否必须手动创建两个不同的用户类以及权限、身份验证等?或者在 django 中是否有针对管理员/用户的单独用户模型?


我尝试过(作为一个完全的业余爱好者,对 oop 和 django 不熟悉)......在放弃使用它作为主键之后,bc AbstractUser 很成功。

尝试使用 onetoonefield,但无法使用 UserCreationForm 制作组合表单,bc“字段过多错误”。将用户表的重要部分放在不同的表中也很奇怪(或者是吗?)。类似(不是 100% 准确):

#in models.py
class AdminUser(AbstractUser):
  username
  email

class NormalUser():
   ontoonefield(AdminUser)
   number(unique=True)

#in forms.py
class NormalUserForm(UserCreationForm):
  class meta:
    fields

class onetoonefieldForm(NormalUserForm):
   class meta:
     add_field += (number)

尝试使用 required_fields,但再次...数字是唯一的

尝试制作两个 abstractUsers... 权限错误

考虑过让它不唯一,然后检查 db insert 是否是唯一的,但这对数据库来说似乎是一种风险,当它至关重要时,它是唯一的。

感谢您的收听:)祝您有美好的一天

标签: djangodjango-modelsdjango-formsdjango-users

解决方案


我是否必须手动创建两个不同的用户类以及权限、身份验证等?或者在 django 中是否有针对管理员/用户的单独用户模型?

Django uses one built in User model and distinguishes three types of users using the attributes is_staff and is_superuser.

  1. Normal user: is_staff=False, is_superuser=False
  2. Staff user (can access the admin interface): is_staff=True
  3. Super user (can do everything): is_superuser=True

If the default user model does not work for you, you can extend it or replace it.

Having the user decide their primary key, is not the intended default. The primary key is usually decided by the database, which also handles the uniqueness. If you would like to assign a unique number to each user, such as a customer number, I suppose it is easiest to extend the user model with a user profile.


推荐阅读