{% if object.url %} not evaluating as expected

I am testing for the availability of an attribute in an object called “url”. Django template evaluates {% if object.url %} to be False or unavailable whereas the attribute exists. object.url evaluates to a string path in a django shell.

Is it possible that django disagrees with the attribute name (i.e. url) since there is also an url tag?: e.g. {% url xxx %} What am I missing?

I suspect that your object.url is Empty String or None. i do not think that there is some naming conflict with the {% url %} tag in Django templates.

If you open a django shell, what is the output of:

print(repr(object.url))
1 Like

This can only be determined within the view that is rendering this template. That view is responsible for ensuring something named object is in the context when the template is rendered. So you’ll need to check the view in order to identify a potential cause.
(The attribute name has nothing to do with this issue, that name is used by a strict lookup sequence as defined at Variables)

Does this object’s url contain anything, or is it an empty string? Because {% if object.url %} will evaluate to false if object.url is an empty string. It isn’t testing whether the attribute exists.

One of the following is the problem:
. You passed an object with the name “object” that is different from what you expected.

. There is no attribute called “url” in the passed object.

. “object” was overwritten in the template.

If you check that the url attribute exists in the shell, in my experience, it is most likely a problem overwritten in the template.

If there is no attribute called url, none should be returned(it would be blank in rendered template), but if false is returned, it is likely that a different object is being used.

you are right. It was a case of empty string though not from object.url . I also had object.value and that was empty.

Therefore my following markup rendered nothing even when object.url had something:
<a href="{{ object.url }}">{{ object.value }}</a>

I was inspecting the wrong object. :man_facepalming:t5:

1 Like