[Answered ]-How to check if a Django CharField is empty

1👍

The problem with your logic is that pronouns will never be '' because it is a model field. If you print(pronouns) when starting the server you will get: <django.db.models.fields.CharField>, not the pronouns of a specific author. The solution is very simple though:

class author(models.Model):
    name = models.CharField(max_length=255, unique=True, help_text='Article author')
    pronouns = models.CharField(max_length=255, help_text='Enter pronouns (optional)', blank=True, verbose_name='Pronouns (optional)')

    def __str__(self):
        if self.pronouns != '':
            return f'{self.name} ({self.pronouns})'
        else:
            return self.name

When you do this you using self you are accessing the field values of the specific instance of author.

Suggestion: Class names should be capitalized: class Author as opposed to class author.

Leave a comment