Assign User to Group Automatically

A snippet for adding users to a default group upon signup or creation.


# signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User, Group

@receiver(post_save, sender=User)
def add_user_to_default_group(sender, instance, created, **kwargs):
    if created:
        group, _ = Group.objects.get_or_create(name='Members')
        instance.groups.add(group)
  

# apps.py

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app'

    def ready(self):
        import your_app.signals
  

# Django Admin

1. Go to /admin/auth/group/
2. Create a group named "Members"
3. Assign permissions to the group as needed
  
Explanation:
  • A post_save signal is triggered every time a new User is created.
  • We check if the user was just created, then add them to a group called Members.
  • If the group doesn't exist, it will be created automatically using get_or_create().
  • We import the signals in apps.py so they're active when the app starts.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.