python runtime_error ai_generated true

jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'username'

ID: python/flask-jinja-undefined-attribute

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Template references a key that is missing from the context dict, or uses dot notation on a dict key that doesn't exist.

generic

中文

模板引用了上下文字典中不存在的键,或对不存在的字典键使用了点号访问。

Workarounds

  1. 90% success
    Use dict .get with default in template:
    {{ user.get('username', 'anon') }}
  2. 92% success
    Ensure the view passes the key:
    return render_template('p.html', user={'username': u.name})

Dead Ends

Common approaches that don't work:

  1. 95% fail

    StrictUndefined makes it raise louder, not fix the missing key.

  2. 60% fail

    If user is a dict without 'username', the attribute access still raises inside the block.