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.
how to set default group for new user in django?
Asked Answered
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'))
I tested, but it didn't set the group. –
Beulabeulah
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'))
–
Beulabeulah 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! –
Usually
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. –
Disappear
© 2022 - 2024 — McMap. All rights reserved.