Django访问/decore_detail/路径时出现TypeError问题求解
解决Django中context必须是dict而非set的TypeError问题
问题场景
访问127.0.0.1:8000/decore_detail/123B/时,期望加载decore_detail.html页面,但运行后抛出错误:
TypeError: context must be a dict rather than set
完整报错栈
Traceback (most recent call last): File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\decoredesigner\mySite\DecoreGenerator\views.py", line 14, in decore_detail return render(request,'decore_detail.html',{'decore_detail',decore_detail}) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\backends\django.py", line 57, in render context = make_context( File "C:\Users\daiyij\Anaconda3\envs\django\lib\site-packages\django\template\context.py", line 278, in make_context raise TypeError( Exception Type: TypeError at /decore_detail/7520N/ Exception Value: context must be a dict rather than set.
问题原因
报错指向views.py第14行的render调用:
return render(request,'decore_detail.html',{'decore_detail',decore_detail})
这里用逗号分隔元素创建的是Python集合(set),但Django的render函数要求第三个参数必须是字典(dict),字典的键值对需要用冒号分隔。
另外你已经定义了正确的字典context = {"decore_detail": decore_detail},但没有在render中使用。
解决方案
修改views.py代码
将render的第三个参数替换为正确的字典,两种方式任选:
方式一:直接使用已定义的context变量
def decore_detail(request, decore_detail): context = {"decore_detail": decore_detail} return render(request, 'decore_detail.html', context)
方式二:直接在render中传入字典
def decore_detail(request, decore_detail): return render(request, 'decore_detail.html', {"decore_detail": decore_detail})
额外修复urls.py的导入问题
你的urls.py中存在导入不一致的问题:已经从myapp.views导入了decore_detail函数,但path里却用了views.decore_detail,修改为统一的写法:
from django.contrib import admin from myapp.views import decore_detail urlpatterns = [ path('admin/', admin.site.urls), path('decore_detail/<str:decore_detail>/', decore_detail, name='decore_detail'), ]
验证修改
修改完成后重新启动Django服务,访问127.0.0.1:8000/decore_detail/123B/,即可正常加载decore_detail.html页面,模板中的{{decore_detail}}会正确渲染出传入的参数值。
内容的提问来源于stack exchange,提问作者Calla
相关产品推荐
相关产品推荐

