Dear all,
What is the proper way of checking if a variable exists in django?
To my knowledge, the proper way is to use the {% if var %} tag. If this is the case, it should not trigger a print in the output (even in the debug log level). Hereafter is an example:
# Note: django 1.10.2
from django.template import Context, Template
context = Context({})
template = Template("{% if avar %}bla{% endif %}")
# output
##################################
DEBUG 2017-02-08 10:19:14,844 base 3090 139658596226880 Exception while resolving variable 'avar' in template 'unknown'.
Traceback (most recent call last):
File "***/python3.4/site-packages/django/template/base.py", line 885, in _resolve_lookup
current = current[bit]
File "***site-packages/django/template/context.py", line 75, in __getitem__
raise KeyError(key)
KeyError: 'avar'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "***site-packages/django/template/base.py", line 891, in _resolve_lookup
if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'Context' has no attribute 'avar'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "***site-packages/django/template/base.py", line 900, in _resolve_lookup
current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'avar'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "***site-packages/django/template/base.py", line 907, in _resolve_lookup
(bit, current)) # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [avar] in "[{'True': True, 'False': False, 'None': None}, {}]"
##################################
I however agree that the following code should generate an debug trace
from django.template import Context, Template
context = Context({})
template = Template("{{ avar }}")
Is there a workaround? Another way to check properly if a variable exists? - Note that I want to see other DEBUG messages, so I don't want to change the log level
Best regards
Florian