python
type_error
ai_generated
true
类型错误:期望整数但收到字符串
TypeError at /api/users/abc/ Expected 'int' but received 'str'
ID: python/django-url-parameter-type
80%修复率
87%置信度
0证据数
2024-06-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.2 | active | — | — | — |
| 4.0 | active | — | — | — |
| 5.0 | active | — | — | — |
根因分析
Django URL 路径参数默认为字符串,但视图函数要求整数
English
URL 路径参数未转换为整数,而视图期望整数类型
解决方案
-
100% 成功率 在 URL 模式中使用 int 转换器
path('users/<int:id>/', views.user_detail) -
90% 成功率 在视图中安全转换
def user_detail(request, id): id = int(id) if isinstance(id, str) else id
无效尝试
常见但无效的做法:
-
在视图中用 int() 强制转换
50% 失败
如果字符串不是数字,int() 会抛出 ValueError
-
修改 URL 模式使用字符串类型
40% 失败
可能破坏其他依赖整数的逻辑