2016-01-21 61 views
0

我正在使用python 2.7 & django 1.7。django - 強制爲Unicode:需要字符串或緩衝區,找不到類型

我有一個模型,我想返回一個字段在模板中使用,但該字段可能爲空,這意味着當我嘗試將條件語句放入返回字段時,我收到此錯誤。

這裏是我的代碼:

class ContactDetails(FillableModelWithLanguageVersion): 
    user = models.ForeignKey(User) 
    contact_details_phone = models.CharField(null=True, blank=True, max_length=30) 
    contact_details_mobile_phone = models.CharField(null=True, blank=True, max_length=30) 
    contact_details_email_address = models.EmailField(null=True, blank=True, max_length=250) 
    contact_details_linkedin_address = models.URLField(null=True, blank=True, max_length=250) 
    contact_details_facebook_address = models.URLField(null=True, blank=True, max_length=250) 
    contact_details_twitter_address = models.URLField(null=True, blank=True, max_length=250) 
    contact_details_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) 
    contact_details_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) 

    def __unicode__(self): 
     return 
     if self.contact_details_mobile_phone: 
      truncatechars(self.contact_details_mobile_phone, 30) 
     elif self.contact_details_phone: 
      truncatechars(self.contact_details_phone, 30) 
     ...... 

當我使用高於如果elif的條件,我收到以下錯誤:

脅迫到Unicode:需要字符串或緩衝區,NoneType發現

我已閱讀此post並應用建議的修復程序,但這不適用於我。這裏是我嘗試過的一個嘗試的示例

def __unicode__(self): 
    return 
    if self.contact_details_mobile_phone: 
     unicode(truncatechars(self.contact_details_mobile_phone, 30)) or u'' 
    elif self.contact_details_phone: 
     unicode(truncatechars(self.contact_details_phone, 30)) or u'' 
    ..... 

我繼續得到相同的錯誤消息。我檢查了數據,數據很好。我想知道如果我濫用if elif條件語法?

有沒有人有我可以嘗試的建議?

+1

您的'__unicode__'方法立即返回None,您需要在if/else子句之後移動return語句。 –

+0

facepalm!是的,這是令人尷尬的。感謝您指出我的愚蠢錯誤。我很專注於我忽略了回報的情況! – user1261774

回答

3

您只是通過return從您的功能返回None。你的函數剛剛在你的if else代碼塊執行之前返回(可能你是一個ruby開發者或者其他東西,但python不能這樣工作)。

+0

謝謝。我不敢相信這個錯誤有多愚蠢!它讓別人看到它。 – user1261774

相關問題