将用户添加到Django中创建组 [英] Adding user to group on creation in Django

查看:634
本文介绍了将用户添加到Django中创建组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有在创建用户后,将此用户的字段指定为True,才希望向用户添加用户。创建的每个用户都将具有与之相关联的UserProfile。这将是实现这种事情的正确方法吗?



models.py:

 code> 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

提前感谢

解决方案

另一个选项是使用 post_save 信号

 django.db.models.signals导入post_save 
从django.contrib.auth.models导入用户,组

def add_user_to_public_group(发件人,实例,创建,* * kwargs):
创建用户信号添加到每个群组的用户。

尝试:
如果创建:
实例。格罗ups.add(Group.objects.get(pk = settings.PUBLIC_GROUP_ID))
除了Group.DoesNotExist:
pass

post_save.connect(add_user_to_public_group,sender = User)

只有使用夹具才能遇到麻烦...(因此,DoesNotExists ..) / p>

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!

解决方案

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

这篇关于将用户添加到Django中创建组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆