python runtime_error ai_generated true

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

ID: python/starlette-template-undefined-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-06-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

The template references a variable attribute that is not present in the context dict passed to TemplateResponse.

generic

中文

模板引用了传递给 TemplateResponse 的上下文字典中不存在的变量属性。

Workarounds

  1. 94% success
    {{ user.get('username', 'guest') }}
  2. 92% success
    return templates.TemplateResponse('p.html', {'request': request, 'user': user or {}})

Dead Ends

Common approaches that don't work:

  1. 85% fail

    StrictUndefined makes the error louder, not absent; it does not supply the missing key.

  2. 80% fail

    Hides the bug and returns a broken page.