# jinja2.exceptions.UndefinedError: 'dict object' 没有属性 'username'

- **ID:** `python/flask-jinja-undefined-attribute`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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

## 无效尝试

- **** — StrictUndefined makes it raise louder, not fix the missing key. (95% 失败率)
- **** — If user is a dict without 'username', the attribute access still raises inside the block. (60% 失败率)
