Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign default group to new user Django

Tags:

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)

like image 706
cildoz Avatar asked Dec 10 '22 04:12

cildoz


1 Answers

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'
like image 162
Willem Van Onsem Avatar answered Jan 20 '23 13:01

Willem Van Onsem