Adding user to group on creation in Django

后端 未结 2 1536
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 01:21

I\'m looking to add a User to a group only if a field of this User is specified as \'True\' once the User is created. Every User that is created would have a \'UserProfile\'

2条回答
  •  無奈伤痛
    2021-01-03 01:55

    Another option is using a post_save signal

    from django.db.models.signals import post_save
    from django.contrib.auth.models import User, Group
    
    def add_user_to_public_group(sender, instance, created, **kwargs):
        """Post-create user signal that adds the user to everyone group."""
    
        try:
            if created:
                instance.groups.add(Group.objects.get(pk=settings.PUBLIC_GROUP_ID))
        except Group.DoesNotExist:
            pass
    
    post_save.connect(add_user_to_public_group, sender=User)
    

    Only trouble you will have is if you use a fixture ... (hence the DoesNotExists .. )

提交回复
热议问题