HBMCS
HBMCS

Reputation: 776

How not to display a field when it's None in Django

I have this model:

class MsTune(models.Model):
    name = models.CharField(max_length=255) # title (source)
    start_page = models.CharField(max_length=20, blank=True, null=True, default=None)

def __str__(self):
        if not self.start_page or self.start_page != '' or self.start_page is not None or self.start_page is not "None" or self.start_page is not null:
            return '%s, %s' % (self.name, self.start_page)
        else:
            return '%s' % (self.name)

As you can see, I want only name if start_page is empty, or name, start_page if start_page is filled. No matter how many conditions I put (see above), I keep getting name, None in my template. What am I missing? Also, is there a shorter code I can put in place, instead of the verbose if / else ?

Edit

This is the content of my field in the database:

mysql> SELECT start_page from bassculture_mstune where id = 1942;
+------------+
| start_page |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)

And in Django's shell:

>>> mytune = MsTune.objects.get(id=1942)
>>> print(mytune.start_page)
None

Upvotes: 0

Views: 1365

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

As default value is going to be "" as from your field, simply checking not value should work:

def __str__(self):
    returnVal = f"{self.name}"
    if self.start_page:
        returnVal = f"{returnVal}, {self.start_page}"
    return returnVal

Or, you can use ternery operation:

def __str__(self):
    return self.start_page and f"{self.name}, {self.start_page}" or f"{self.name}" 

Python ternary operation: Refs

Upvotes: 1

Related Questions