2012-03-19 72 views
1

我有一個剖面模型:如何在GAE中獲取或創建用戶配置文件?

class Profile(db.Model): 
    user = db.UserProperty(auto_current_user=True) 
    bio = db.StringProperty() 

我想在此視圖中顯示用戶的現有生物。如果用戶還沒有配置文件,我想創建它。這是我迄今爲止,還沒有工作:

class BioPage(webapp2.RequestHandler): 
    def get(self): 
     user = users.get_current_user() 
     if user: 
      profile = Profile.get_or_insert(user=user) #This line is wrong 
      profile.bio = "No bio entered yet." 
      profile.save() 
      self.response.headers['Content-Type'] = 'text/plain' 
      self.response.out.write('Hello, ' + user.nickname() + '<br/>Bio: ' + profile.bio) 
     else: 
      self.redirect(users.create_login_url(self.request.uri)) 

如何解決上述不正確的行?我知道get_or_insert()應該有一個關鍵名稱,但我無法弄清楚會是什麼。

(應該在配置文件中的用戶場均是db.UserProperty?)

回答

2

你必須通過key_nameget_or_insert(),在這種情況下,像這樣:

profile = Profile.get_or_insert(key_name=user.email()) 

注意,由於user屬性由於auto_current_user=True而自動填充,因此您無需將其傳遞給get_or_insert()調用。在你的情況下,你不需要傳遞任何東西,除了關鍵的名字。

1

您可能不想使用db.UserProperty,原因解釋爲here。總之,如果用戶更改他/她的電子郵件地址,則(舊)存儲的「用戶」不會與當前登錄的(新)「用戶」相等。

而是將user.user_id()存儲爲Profile模型上的StringProperty(如上面引用的頁面所示)或Profile模型的key(key_name)。後者的一個例子是here

相關問題