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.
Asked
Active
Viewed 6,131 times
1 Answers
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'))

Dalvtor
- 3,160
- 3
- 21
- 36
-
I tested, but it didn't set the group. – Ali Soltani Jan 31 '18 at 14:52
-
1This 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'))` – Ali Soltani Jan 31 '18 at 15:14
-
2Oh!! 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 '18 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 '20 at 18:26