2

I've got a portion of my app that allows a custom logo.

Default object (and object view) state is no custom logo, but if one exists, replace the header with a custom logo navbar.

logo is a standard ImageField on co(mpany) model:

models.py:

class Co(models.Model): logo = models.ImageField(blank=True) 

template:

{% if co.logo %} {% block navbar %} {% include 'templates/navbar_logo.html' %} {% endblock %} {% endif %} 

I've also tried this with {% if co.logo == None %}, {% if not ... %}, {% if co.logo.url %} and trying to model the logic with co.logo|default_if_none:"" but in instances where a logo isn't set the view throws:

ValueError at /co/foo The 'logo' attribute has no file associated with it.

for... empty also doesn't work

{% for co.logo.url in co %} ... {% empty %} ... {% endfor %} 

in django shell:

(with logo)

c.logo >> <ImageFieldFile: logo.png> c.logo.url >> '/media/logo.png' 

(no logo)

b.logo >> <ImageFieldFile: None> 

is there a built in django template tag filter that will allow this condition to pass True only if the field has an image uploaded? otherwise don't load the nav block? thanks

2 Answers 2

3

I solved this by re-ordering the tags:

{% block navbar %} {% if co.logo %} {% include 'templates/navbar_logo.html' %} {% else %} {% include 'templates/navbar.html' %} {% endif %} {% endblock %} 
Sign up to request clarification or add additional context in comments.

Comments

2

Try Use 'is not null'

{% if co.logo.url is not null %} {% block navbar %} {% include 'templates/navbar_logo.html' %} {% endblock %} {% endif %} 

2 Comments

also in models.py set null=True
This does not work in newer versions of django, as block is always evaluated! See the other answer about re-ordering! (block needs to be outermost)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.