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

问题描述 投票:3回答:1

我在创建自定义用户模型的两个教程之间来回走动:

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)

此时,我已经碰壁了。我不确定将内容限制为用户的方向。我的一般想法是,我希望管理员访问所有内容,让区域管理员具有下一个访问级别,然后是站点管理员,然后让普通用户(在所有布尔检查中为false)具有基本特权。

这是进行这种实现的最佳途径吗?我应该从这里去哪里,为什么?

django django-models django-forms django-admin django-users
1个回答
0
投票

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

如果您需要向用户添加更多信息,通常的模式是创建UserProfile:

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

一些建议:

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