Undefined Variable

Debug undefined variable errors

2 min read 358 words

DebugUndefinedErrorexceptions.

The Error

UndefinedError: Undefined variable 'usre' in page.html:5

Common Causes

1. Typo in Variable Name

{# ❌ Typo #}
{{ usre.name }}

{# ✅ Correct #}
{{ user.name }}

Fix: Check spelling against what's passed torender().

2. Variable Not Passed to Template

# ❌ Missing variable
template.render(title="Hello")

# ✅ Include all needed variables
template.render(title="Hello", user=current_user)

Fix: Ensure all template variables are passed inrender().

3. Wrong Attribute Name

{# ❌ Wrong attribute #}
{{ user.nmae }}

{# ✅ Correct attribute #}
{{ user.name }}

Fix: Verify object attributes match your code.

4. Nested Object is None

{# ❌ parent might be None #}
{{ page.parent.title }}

{# ✅ Check first #}
{% if page.parent %}
    {{ page.parent.title }}
{% end %}

Fix: Use conditional checks ordefaultfilter.

Solutions

Use default Filter

{{ user.nickname | default("Anonymous") }}
{{ config.timeout | default(30) }}

Check with is defined

{% if user is defined %}
    {{ user.name }}
{% else %}
    Guest
{% end %}

Optional Chaining Pattern

{% if post and post.author %}
    {{ post.author.name }}
{% end %}

Safe Navigation

{{ user | default({}) | attr("name") | default("Unknown") }}

Debug Tips

# In Python
print(context.keys())

Use debug Filter

{{ user | debug }}

Output (to stderr):

DEBUG: <User>
  .name = 'Alice'
  .email = 'alice@example.com'

Check Template Context

def render_debug(template_name, **context):
    print(f"Rendering {template_name}")
    print(f"Context keys: {list(context.keys())}")
    return env.render(template_name, **context)

Prevention

Type Hints for Context

from dataclasses import dataclass

@dataclass
class PageContext:
    title: str
    user: User
    items: list[Item]

# IDE will catch missing fields
context = PageContext(title="Hello", user=user, items=items)
template.render(**asdict(context))

Template Validation

def validate_context(context, required):
    missing = [k for k in required if k not in context]
    if missing:
        raise ValueError(f"Missing: {missing}")

See Also