Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading