Adding user to group on creation in Django

2020-03-04 11:58发布

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' associated with it. Would this be the correct way to implement such a thing?

models.py:

def add_group(sender, instance, created, **kwargs):
    if created:
        sender = UserProfile
        if sender.is_in_group:
            from django.contrib.auth.models import Group
            g = Group.objects.get(name='Some Group')
            g.user_set.add(sender)

post_save.connect(add_group, sender=UserProfile)

Thanks in advance!

2条回答
【Aperson】
2楼-- · 2020-03-04 12:41

try this:

def save(self, *args, **kwargs):
    # `save` method of your `User` model

    # if user hasnt ID - is creationg operation
    created = self.id is None
    super(YourModel, self).save(*args, **kwargs)

    # after save user has ID
    # add user to group only after creating
    if created:
        # adding to group here
查看更多
够拽才男人
3楼-- · 2020-03-04 12:52

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 .. )

查看更多
登录 后发表回答