python
type_error
ai_generated
true
TypeError at /api/users/abc/ Expected 'int' but received 'str'
ID: python/django-url-parameter-type
80%Fix Rate
87%Confidence
0Evidence
2024-06-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.2 | active | — | — | — |
| 4.0 | active | — | — | — |
| 5.0 | active | — | — | — |
Root Cause
URL 路径参数未转换为整数,而视图期望整数类型
generic中文
Django URL 路径参数默认为字符串,但视图函数要求整数
Workarounds
-
100% success 在 URL 模式中使用 int 转换器
path('users/<int:id>/', views.user_detail) -
90% success 在视图中安全转换
def user_detail(request, id): id = int(id) if isinstance(id, str) else id
Dead Ends
Common approaches that don't work:
-
在视图中用 int() 强制转换
50% fail
如果字符串不是数字,int() 会抛出 ValueError
-
修改 URL 模式使用字符串类型
40% fail
可能破坏其他依赖整数的逻辑