cildoz
cildoz

Reputation: 436

Assign default group to new user Django

I'm trying to assign a group to every new user registered into the system. I've already read something about it in another questions but I don't really know where to add the necessary code to make it work.
I'm using Django 2.1.3 and I'm logging users using allauth (social login, but it shouldn't make any difference as a new instance in the User table is created)

Upvotes: 4

Views: 2338

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476740

You can use a @post_save signal for example that, each time a User is created, adds the given group to the groups of the User. Typically signals reside in a file named handlers.py in the signals directory of an app, so you probably should create or modify the files listed in boldface:

app/
    signals/
        __init__.py
        handlers.py
    __init__.py
    apps.py
    ...
# app/signals/handlers.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import Group

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_profile(sender, instance, created, **kwargs):
    if created:
        g1 = Group.objects.get(name='group_name')
        instance.groups.add(g1)

where group_name is the name of the group you want to add.

You should then import the handlers.py module in your MyAppConfig (create one if you do not have constructed such config yet):

# app/apps.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'app'
    verbose_name = "My app"

    def ready(self):
        import app.signals.handlers

and register the MyAppConfig in the __init__.py of the app:

# app/__init__.py

default_app_config = 'app.apps.MyAppConfig'

Upvotes: 10

user2390182
user2390182

Reputation: 73470

If this should happen for any new User instance, you can connect a handler to the post_save signal:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def handle_new_job(sender, **kwargs):
    if kwargs.get('created', False):
        user = kwargs.get('instance')
        g = Group.objects.get(name='whatever')
        user.groups.add(g)

Include this code in your app and make sure it is imported as stated e.g. here.

Upvotes: 3

Related Questions