Search code examples
pythondjangodjango-formsdjango-authentication

Set is_staff to true for new users that created new accounts from CreateView


I am having problem with Django.

I am using UserCreationForm and generic CreateView in order for people to sign up and create an account. The code is as follows:

Custom form:

class SignUpCustomUserForm(UserCreationForm):
    first_name = forms.CharField(max_length=200)
    last_name = forms.CharField(max_length=200)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']

View:

class SignUpView(generic.CreateView):
    form_class = SignUpCustomUserForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

I do not have a model since I am using CreateView which basically handles the model.

I want to automatically set every new created account as staff, but I can not figure out how to do it. Basically, I am working on a form which users can use to create an account with is_staff privileges and they can use those accounts to login to /admin (the default django admin).

I tried setting model.is_staff to true in the Meta class inside the form class, but it didn't work out.

Any advice or ideas is welcomed.

Thank you


Solution

  • You can set is_staff to True in the .form_valid(…) method:

    class SignUpView(generic.CreateView):
        form_class = SignUpCustomUserForm
        success_url = reverse_lazy('login')
        template_name = 'registration/signup.html'
        
        def form_valid(self, form):
            form.instance.is_staff = True
            return super().form_valid(form)