0

I am using python 2.7 & django 1.7.

I have a model that I want to return a field to be used in a template, however that field may be blank, which means that I receive this error when I attempt to place a condition statement to the return field.

Here is my code:

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

When I apply the if elif condition above, I receive the following error:

coercing to Unicode: need string or buffer, NoneType found

I have read this post and applied the suggested fixes, but this does not work for me. Here is an example of one attempt I have tried

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

I continue to get the same error message. I have checked the data and the data is good. I am wondering if I have misused the if elif condition syntax?

Does anyone have a suggestion I could attempt?

Community
  • 1
  • 1
user1261774
  • 3,525
  • 10
  • 55
  • 103
  • 1
    Your `__unicode__` method returns None immediately, you need to move the return statement after your if/else clause. – Derek Kwok Jan 21 '16 at 22:01
  • facepalm! Yes that is embarrassing. Thanks for pointing out my stupid error. I was so focused on the condition I neglected the return! – user1261774 Jan 21 '16 at 23:23

1 Answers1

3

You returned None from your function by doing just return. Your function just returned earlier before your if else code block executed(maybe you were a ruby developer or something but python doesn't work like that).

Shang Wang
  • 24,909
  • 20
  • 73
  • 94