我希望仅在将此用户的字段指定为' True'一旦创建了用户。创建的每个用户都将拥有一个“用户配置文件”。与之相关联。这是实现这种事情的正确方法吗?
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)
提前致谢!
答案 0 :(得分:1)
另一种选择是使用post_save
信号
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)
如果您使用灯具,那么您只会遇到麻烦......(因此不会出现这种情况......)
答案 1 :(得分:0)
试试这个:
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