在Django自定义身份验证模型中创建超级用户

时间:2020-05-18 05:18:52

标签: python django django-authentication django-users

我想在我的自定义授权用户模型中创建一个超级用户。 这是我的模型。py

class User(AbstractUser):
    is_Admin = models.BooleanField(default=False)
    is_HR = models.BooleanField(default=False)
    is_MGR = models.BooleanField(default=False)
    is_EMP = models.BooleanField(default=True)


class Admins(models.Model):

    def __str__(self):
        return self.user.username

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user.is_admin = True
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)


我希望Admins模型能够访问所有用户数据,并访问Django管理页面。 以下是我的管理员创建视图-

class AdminSignUpView(CreateView):
    model = User
    form_class = AdminSignUpForm
    template_name = 'form1/signup_form.html'

    def get_context_data(self, **kwargs):
        kwargs['user_type'] = 'ADMIN'
        return super().get_context_data(**kwargs)
    def form_valid(self, form):
        user = form.save()

        return redirect('/P/login_page/')

管理员的表单是-

class AdminSignUpForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = User
    fname = forms.CharField(label = 'First Name', max_length=256)
    lname = forms.CharField(label = 'Last Name', max_length=256)
    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.save()

        user.is_Admin = True
        user.save()
        admin1 = Admins.objects.create(user=user)
        admin1.first_name=(self.cleaned_data.get('fname'))
        admin1.last_name=(self.cleaned_data.get('lname'))
        return user

我好几个星期都没弄清楚。我做错什么了吗? 我希望能够使用内置的Django Auth UI来编辑,创建和删除用户,同时还要保持我的自定义Auth模型以及四个不同的层次结构。

1 个答案:

答案 0 :(得分:0)

创建自定义视图以创建管理员

from django.contrib.auth.models import User

def new(request):
    if request.method == "POST":
            form = RegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                user = User.objects.create_user(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password'],
                    email=form.cleaned_data['email'],
                    first_name=form.cleaned_data['first_name'],
                    last_name=form.cleaned_data['last_name'],
                    is_staff=True,
                    is_active=True,
                    is_admin=True,
                )
            else:
                print (form.errors)
                return HttpResponse("Validation Error")

            return HttpResponse("Success")
        else:

            context = {
                "form" : form,
            }
            return render(request, 'form.html',context)