用于创建具有不同权限的用户的Django表单

时间:2018-07-24 19:35:56

标签: django django-custom-user

我正在使用Django系统,该系统有四个级别的用户: 1.基本(仅限访问权限) 2.管理员(可以更新/更改/删除) 3.网闸(只能创建管理员用户,不能更新/更改/删除) 4.开发人员(真正的超级用户)

我认为我已经弄清楚了一些权限:

    from django.conf import settings
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from django.core.validators import RegexValidator
from django.db import models
from django.db.models.signals import post_save


class CustomUserManager(BaseUserManager):
    """Customer User."""

    def create_user(self, email, password=None):
        """Creates and saves a user."""
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_admin(self, email):
        """Creates and saves an admin user with a temporary password."""
        user = self.create_user(
            email,
            password=BaseUserManager.make_random_password(self, 12)
        )
        user.is_admin = True
        user.save(using=self.db)
        return user


    def create_gatekeeper(self, email, password):
        """Creates and saves a gatekeeper."""
        user = self.create_user(
            email,
            password=password,
        )
        user.is_admin = True
        user.is_gatekeeper = True
        user.save(using=self.db)
        return user

    def create_superuser(self, email, password):
        """Creates and saves a superuser."""
        user = self.create_user(
            email,
            password=password,
        )
        user.is_admin = True
        user.is_gatekeeper = True
        user.is_developer = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_gatekeeper = models.BooleanField(default=False)
    is_developer = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    # def __str__(self):
    #     return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        # Does the user have a specific permission?
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        # "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    class Meta:
        db_table = 'customuser'
        verbose_name = 'CustomUser'

但是,我没有与如何创建网守和管理员建立联系。我知道我可以通过命令行来做到这一点,但是我想要

a)开发人员可以创建网守的形式 b)看门人可以创建管理员的表单

由于我们的管理站点需要进行大量的自定义,因此我们将不会使用Django Admin,并且可能会构建自己的功能。我该如何在Django表单中调用create_gatekeeper之类的东西?子类化Django Admin页面并对其进行自定义会是更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可能应该使用网上论坛,并向这些网上论坛添加权限;;;但是在您的3个Actor中,您可以使用User模型中的django内置属性...

用户:您的常规用户只是使用is_something ...

身份创建为User类。

管理员,您可以使用属性is_staff,该属性来自用户模型,并允许您的用户访问django管理员...

开发人员,您可以将其创建为超级用户,因此所有权限都将自动添加到模型中

问题是关守,因此,如果您开始创建is_admin,is_gatekeeper等标记,您将开始处理多个属性,这是一个糟糕的想法,因此在使用组时,您可以创建User组,开发人员组(因为他们实际上是超级管理员,因此您实际上不需要这样做),管理组(向该组添加要授予的每个权限[例如,您可以向他提供博客的博客模型,博客add_blog,change_blog和delete_blog,但是您也可以添加您的自定义]],与其他组相同...

例如。

# List of my Permissions that i want to add to my groups
PERMISSIONS = {
    STUDENT : ['add_student', 'change_student',
                  'delete_student', 'editpreview_student'],
    PROJECT: ['add_project', 'change_project', 'delete_project', 'editpreview_project'],

}

# Creating 2 Groups
grupo_admin, created = Group.objects.get_or_create(name='admin') 
grupo_teachers, created = Group.objects.get_or_create(name='teacher')    


for func_perm in PERMISSIONS [STUDENT]:
    perm = Permission.objects.get(codename=func_perm)
    grupo_admin.permissions.add(perm) # Adding Student Permission to my Admin Group
    grupo_teachers.permissions.add(perm)  # Adding Student Permission to my Teachers Group
for func_perm in PERMISSOES[PROJECT]:
    perm = Permission.objects.get(codename=func_perm)
    grupo_admin.permissions.add(perm) # Adding Project Permission only to my Admin Group

在您看来,您可以像这样检查权限

@user_passes_test(lambda u: u.has_perm('myapp.permission_code'))
def some_view(request):
    # ...

您可以像这样检查HTML

{% if perms.student.change_student %}
  <li>
    <a href="/admin/student/student/">
      <i class="fa fa-graduation-cap" aria-hidden="true"></i> 
      <span>Students</span>
    </a>
   </li>  
{% endif %}