0

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.

Doug Smith
  • 500
  • 7
  • 21

2 Answers2

2

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', 'lennon@thebeatles.com', 'johnpassword')
user.is_staff = True
user.save()
group = Group.objects.get(name='Group name')
user.groups.add(group) 
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • 1
    Where would that code go? Is it possible to automatically query the db when a user is created so the model is changed? I'm using allauth, so I don't have my own view for signup/registrations. – Doug Smith Aug 22 '18 at 20:54
  • 1
    This worked for me, by adding the code in the `form_valid` function described [here](https://stackoverflow.com/a/28974691/3976696). – sc28 Mar 15 '19 at 12:52
1

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()
  • Is that in views.py? – Doug Smith Aug 22 '18 at 22:33
  • From the docs:Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code. In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready()." – Doug Smith Aug 23 '18 at 02:38
  • 1
    I had to add `instance.save()` at the end of Mohammad Torkashvand's solution in order to save `is_staff`. Good solution. Other link that helps with putting this all together is: [Where should signal handlers live in a django project?](https://stackoverflow.com/questions/2719038/where-should-signal-handlers-live-in-a-django-project) – Doug Smith Aug 23 '18 at 03:46
  • @DougSmith. you are right. I added it at the end. :) – Mohammad Torkashvand Aug 23 '18 at 07:44