Django新手求助:TypeError: __init__()参数不匹配问题排查
解决Django的TypeError和URL路径错误问题
看起来你遇到了几个新手常犯的Django典型问题,咱们一步步拆解解决:
1. 视图函数参数错误(核心TypeError原因)
你把普通函数视图写成了类方法的形式——函数视图的第一个参数必须是request,而不是self。Django调用视图时,会自动传入request对象和URL捕获的pk参数,当前的参数定义会导致参数不匹配,直接触发TypeError:
错误的views.py代码:
def details(self, pk): print('1') Testimony=get_object_or_404(Testimony, pk= pk) print('2') return render(request, 'details.html', {'Testimony': Testimony})
修正后的views.py代码:
def details(request, pk): # 把self替换为request print('1') testimony = get_object_or_404(Testimony, pk=pk) # 变量名小写更符合Python编码规范 print('2') return render(request, 'details.html', {'testimony': testimony}) # 上下文变量名统一为小写
2. URL配置错误
你使用了re_path但套用了path的路径转换器语法(<int:pk>),re_path是基于正则表达式的配置项,需要用正则写法;如果想用<int:pk>这种简洁的转换器,应该改用path:
推荐的urls.py修正方案(用path):
from django.urls import path # 确保导入path urlpatterns = [ # ... 其他URL配置 path('<int:pk>/', views.details, name='details'), ]
如果一定要用re_path,则需要写成正则表达式形式:
from django.urls import re_path urlpatterns = [ # ... 其他URL配置 re_path(r'^(?P<pk>\d+)/$', views.details, name='details'), ]
3. 模板URL反向解析错误
你的模板里用了Testimony.pk(大写T),但上下文传递的变量是testimony(小写t),大写的Testimony是模型类名而非实例,无法正确获取pk值,导致生成的URL路径出现编码错误(/%3Cint:pk%3E.pk):
错误的模板代码:
<h1><a href="{% url 'details' Testimony.pk %}">{{testimony.Title}}</h1>
修正后的模板代码:
<h1><a href="{% url 'details' testimony.pk %}">{{testimony.Title}}</a></h1> <!-- 补上闭合的</a>标签 -->
完成以上三步修正后,记得重启Django开发服务器确保代码生效,你的问题应该就能解决了!
内容的提问来源于stack exchange,提问作者HAN YAO FOONG
相关产品推荐
相关产品推荐

