[Answer]-Declare variable if variable declared already

1👍

You can’t (easily) do that with django’s template language. This is by design. The documentation mentions this specifically:

the template system is meant to express presentation, not program logic.

Instead, it would be much easier to write a simple method on your profile model:

class Profile(models.Model):
    ...

    def pronoun(self):
        if self.gender == 'F':
            return "her"
        elif self.gender == 'M':
            return "him"
        return "them"

and call that instead:

{{ user.get_profile.pronoun }}

An alternative to this would be to write a template filter that you could use on the attribute that would take the value of the gender field and return the appropriate string. This would be useful if you were planning to reuse the function

@register.filter(name='gender_pronoun')
def gender_pronoun(value):
    if self.gender == 'F':
        return "her"
    elif self.gender == 'M':
        return "him"
    return "them"

and call it like so in the template

{{ user.get_profile.gender|gender_pronoun }}

Leave a comment