9

I was getting a VariableDoesNotExist error with the following snippet when obj1.page is None.

{{ obj1.val1|default:obj1.page.val2 }}

Normally Django templates don't care about attribute accesses on None values.

Kamlesh
  • 2,032
  • 2
  • 19
  • 35
Seán Hayes
  • 4,060
  • 4
  • 33
  • 48

2 Answers2

15

Django only cares about attribute lookups on None values inside the default template filter. I got around it using:

{% with obj1.page.val2 as val2 %}
{{ obj1.val1|default:val2 }}
{% endwith %}
Seán Hayes
  • 4,060
  • 4
  • 33
  • 48
  • 6
    Note to future googlers: https://code.djangoproject.com/ticket/13167 explains that this bug is not expected to ever be fixed, because they think it will introduce more problems than it fixes. So expect this workaround to be useful for the foreseeable future. – coredumperror May 14 '18 at 22:02
  • 2
    @CoreDumpError It looks like it's been reopened: https://code.djangoproject.com/ticket/28172 but it's marked as "Someday/Maybe" – gdvalderrama Sep 09 '19 at 15:08
0

VariableDoesNotExist bcoz it's not created in the session...so to create

views.py(in get method)

Variable_Name = request.session.get('Variable_Name') if not Variable_Name: request.session.Variable_Name = {} #Here we create a dictionary