Doug Smith
Doug Smith

Reputation: 580

How to automatically add group and staff permissions when user is created

I'm runnging Django 2.0.8 and currently using django-allauth.

When a new user registes/signs up, I would like them to automatically be added to a group and given staff status so they can log into the admin page.

I've read some of the documentation but I currently don't understand how it all ties together and each new user is defaulted to some permissions.

Upvotes: 0

Views: 3938

Answers (2)

Torkashvand
Torkashvand

Reputation: 416

In this case if you don't have access to User model and it's save function you can add your logic in post save signal.

@receiver(models.signals.post_save, sender=User)
def post_save_user_signal_handler(sender, instance, created, **kwargs):
    if created:
       instance.is_staff = True
       group = Group.objects.get(name='Group name')
       instance.groups.add(group)
       instance.save()

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47364

To mark new user as staff use is_staff attribute. To add user to the group fetch Group object from DB and add it to the user using user.groups.add(group):

from django.contrib.auth.models import Group

user = User.objects.create_user('john', '[email protected]', 'johnpassword')
user.is_staff = True
user.save()
group = Group.objects.get(name='Group name')
user.groups.add(group) 

Upvotes: 2

Related Questions