django - 强制转换为Unicode:需要字符串或缓冲区,找到NoneType

时间:2016-01-21 21:57:06

标签: python django unicode django-models django-templates

我正在使用python 2.7& django 1.7。

我有一个模型,我想返回一个要在模板中使用的字段,但是该字段可能是空白的,这意味着当我尝试将条件语句放入返回字段时收到此错误。

这是我的代码:

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)
        ......

当我应用上面的if 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 个答案:

答案 0 :(得分:3)

您仅通过None从您的函数返回return。您的函数刚刚在执行if else代码块之前返回(可能您是一个红宝石开发人员或其他东西,但python不能像那样工作)。