在我的 Django 应用程序中实现用户类型限制

Implementing user type restrictions in my Django application

我一直在两个关于创建自定义用户模型的教程之间来回切换:

https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html

https://wsvincent.com/django-tips-custom-user-model/

到目前为止,这是我的代码:

型号:

class CustomUser(AbstractUser):
    is_admin = models.BooleanField('admin status', default=False)
    is_areamanager = models.BooleanField('areamanager status', default=False)
    is_sitemanager = models.BooleanField('sitemanager status', default=False)

表格:

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser

class CustomUserChangeForm(UserChangeForm):

    class Meta(UserChangeForm.Meta):
        model = CustomUser

管理员:

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username',]

admin.site.register(CustomUser, CustomUserAdmin)

此时我有点碰壁了。我不确定向用户限制内容的方向。我的总体想法是我希望管理员能够访问所有内容,区域经理拥有下一级访问权限,之后是站点管理员,然后是普通用户(所有布尔检查均为假)拥有基本权限。

这是实现此类实施的最佳途径吗?我应该从这里去哪里?为什么?

不要扩展 AbstractUser,用户 Django 内置组和权限来创建 class 具有不同权限的用户: https://docs.djangoproject.com/en/3.0/topics/auth/default/#groups

如果您需要向用户添加更多信息,常见的模式是创建用户配置文件:

class UserProfile(models.Model):  
    user = models.OneToOneField(User, related_name='profile')
    address = models.CharField(max_length=140)  
    age = ...

几个建议:

  • 仅在特定用例的情况下使用 AbstractUser(例如,当您需要自定义 AuthenticationBackend 时)
  • 在模型中使用用户 ID 而不是用户配置文件 ID 作为 FK(从请求中检索它更容易)
  • 对于基本用例,只需向 UserProfile 添加一个 'role' 字段就足以实现一个简单的逻辑