2013-07-03 31 views
1

我一直在使用Django一段时间,但这不是一个错误,但我想找出 为什么create_profile方法需要保存配置文件和创建的变量?Django:配置文件和创建变量

@receiver(post_save, sender=User) 
def create_profile(sender, instance, created, **kwargs): 
    if created: 
     profile, created = UserProfile.objects.get_or_create(user=instance) 

我已经试过

print >> sys.stderr , "create_user" + str(profile) + (str(created)) 

,他们返回User_Profile UNICODE函数的返回值和所创建的一个布尔值。

我的问题具体是存储配置文件,创建值的意义。

UserProfile.objects.get_or_create(user=instance) 

我已经试过单独调用语句,它的作品

+0

你从哪里收到错误? – Koterpillar

+1

错误可能是在打印语句中,如果你没有删除它,因为你没有更多的变量称为简介 –

+0

是的我犯了一个错误错误是在打印声明 – laycat

回答

1

没有必要将调用的结果分配给任何变量如果你不需要他们。所以

UserProfile.objects.get_or_create(user=instance) 

很好。

如果你只使用一个变量,而不是其他(由错误判断):

profile, _ = UserProfile.objects.get_or_create(user=instance) 
2

这是一个常见的做法去做,如果你打算以后使用它们:

profile, created = UserProfile.objects.get_or_create(user=instance) 
if profle.check_something_here: 
    return profile.something_else 

或可能:

profile, created = UserProfile.objects.get_or_create(user=instance) 
if created: 
    # do something with the newly created profile 
else: 
    # do something else if the profile was already there 

这当然如果你需要做的事情与他们。否则UserProfile.objects.get_or_create(user=instance)也是正确的。