2013-07-03 67 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)也是正確的。

相關問題