django自定义用户模型用户创建问题:权限不起作用

时间:2019-04-28 19:30:32

标签: python django model permissions

我正在django中创建自定义用户模型,但是以某种方式通过创建表单创建的任何新用户都缺少其分配的权限(is_active,is_staff,is_admin),从而根本无法登录。

有人可以告诉我我哪里出了错吗?任何建议都将不胜感激!

代码段:

models.py

class CustomUserCreationForm(UserCreationForm):
    ID = forms.CharField(max_length=50)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta(UserCreationForm):
        model = employee
        fields = "__all__"

class CustomUserChangeForm(UserChangeForm):
    ID = forms.CharField(max_length=50)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = employee
        fields = "__all__"

forms.py

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    add_form = CustomUserChangeForm
    form = CustomUserChangeForm
    model = employee

    list_display = ('ID', 'name', 'email', 'privilege')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('ID', 'password')}),
        ('Personal info', {'fields': ('name', 'email', 'privilege')}),
        ('Permissions', {'fields': ('is_admin', 'is_staff', 'is_active')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('ID', 'name', 'email')}
        ),
    )
    search_fields = ('name',)
    ordering = ('ID',)
    filter_horizontal = ()

admin.py

def employee_list(request):
    data_list = Employee.objects.order_by('NIP')
    registered = False

    if request.method == "POST":
        if 'add_user' in request.POST:
            user_form = CustomUserCreationForm(request.POST, prefix='add')

            if user_form.is_valid():
                new_user = user_form.save()
                new_user.set_password(user.password)
                new_user.save()
                registered = True

            return HttpResponseRedirect(reverse('employee'))

    else:
        user_form = CustomUserCreationForm(prefix='add')

    return render(request, 'employee_list.html',
                            {'SignUpForm': user_form,
                            'registered': registered,
                            'Emp_list':data_list})

views.py

{{1}}

1 个答案:

答案 0 :(得分:0)

不是在个人输入很容易出错的 Employee 模型中使用“特权”作为字符字段,而是使用选择字段。

class MyUserManager(BaseUserManager):
use_in_migrations = True

def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):

    if not email:
        raise ValueError('Users must have an email address')

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

    user.set_password(password)
    user.is_active = True
    user.is_staff = is_staff
    user.is_admin = is_admin
    user.save(using=self._db)
    return user

def create_superuser(self, name, email, password):
    new_user = self.create_user(
        name,
        email,
        privilege='admin',
        password=password,
        is_staff=True,
        is_admin=True
    )
    return new_user


class Employee(AbstractBaseUser):
    PRIVILEGE_LEVEL = (
        ('Administrator', 'admin'),
        ('Staff', 'staff'),
        ('Member', 'member'),
    )

    # ID = models.IntegerField(verbose_name="ID", unique=True)
    id = models.AutoField(primary_key=True)
    name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True)
    email = models.EmailField(verbose_name="email", max_length=225, default='this@mail.com')
    Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='')
    Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='')
    # privilege = models.CharField(max_length=10, default='User')
    privilege = models.CharField(max_length=120, choices=PRIVILEGE_LEVEL, default='member')
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

此外,django会自动生成“ id”作为主键字段,因此它不必采用前端形式。

  

默认情况下,Django模型表单调用 MyUserManager.create_user 。   并根据我在上面所做的修改,默认情况下为创建用户   没有权限。除非 is_admin is_staff 隐式设置为 True

要从当前表单创建 超级用户 ,您可以像这样更新 MyUserManager.create_user

def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):

    if not email:
        raise ValueError('Users must have an email address')

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

    user.set_password(password)
    user.is_active = True
    user.is_staff = is_staff
    user.is_admin = is_admin
    if privilege == 'admin':
        user.is_superuser = True
    user.save(using=self._db)
    return user

但是我建议您更新 CustomUserCreationForm

class CustomUserCreationForm(UserCreationForm):
# ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)

class Meta(UserCreationForm):
    model = Employee
    fields = "__all__"

# ADD THIS
def clean(self, value):
    print(self.data)
    print(self.errors)
    cleaned_data = self.cleaned_data
    print(cleaned_data)
    return cleaned_data
# ADD THIS

def save(self, *args, **kwargs):
    data = self.cleaned_data
    # email, password1 = v['email'], v['password1']
    employee = None
    if data['privilege'] == 'admin':
        employee = Employee.objects.create_superuser(
            name=data['name'],
            email=data['email'],
            password=data['password'],
        )
    else:
        employee = Employee.objects.create_user(
            name=data['name'],
            email=data['email'],
            password=data['password'],
        )
    # User is already saved after calling BaseUserManager function.
    return employee
  

MyUserManager.create_superuser 调用 MyUserManager.create_user 并根据传递给它的参数对其进行更新。

如果您需要进一步说明,请告诉我。干杯。