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)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With