5

how can I set default group for new users that I create? I didn't create custom model of user and My django version is 1.11.

1 Answer 1

11

If you are not using custom user models, or proxy models, one possible option is to use signals, so whenever a user is created, you can assign the corresponding group:

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

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        instance.groups.add(Group.objects.get(name='group_name'))
4
  • I tested, but it didn't set the group. Jan 31, 2018 at 14:52
  • 1
    This worked for me: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: instance.groups.add(Group.objects.get(name='group_name')) Jan 31, 2018 at 15:14
  • 2
    Oh!! of course!! Silly me, I forgot that group was a many to many field, and I posted my answer from memory. Sorry! Glad you figured it out, I will update the question for next users. Mark it as accepted if you wish to help more people!
    – Dalvtor
    Jan 31, 2018 at 15:18
  • Also note that this many to many relationship needs an Id so you can't override save method even if you code a custom user model.
    – Ehsan88
    Sep 11, 2020 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.