【发布时间】:2019-05-08 11:39:37
【问题描述】:
我最近从 Django 1.9 切换到 1.11.17,有一件事让我很困扰。有这个错误说
TypeError at /somepath
context must be a dict rather than Context
抛出它的那一行是:
return render(request=request, template_name="mytemplate.html", context={"form": form, "update": updateType})
关于 SO 有很多答案,人们使用 RequestContext 或 Context 而不是 dict 来表示 context 并且切换到 dict 可以解决他们的问题。但不适合我。在这里,我很确定我的context 实际上是一个字典。如果我将其更改为:
return render(request=request, template_name="mytemplate.html", context={})
错误消失了,但显然稍后会导致另一个错误。你们知道我在这里做错了什么吗?
编辑: 我的进口:
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext, Context
我尝试过 bot render 和 render_to_response 具有类似的效果。也使用 Context 或 RequestContext 给出了类似的错误。
EDIT2:更多代码供参考
from django.http import (
HttpResponseRedirect,
HttpResponseBadRequest,
)
from django.shortcuts import render, render_to_response
from django.template import RequestContext, Context
from django.utils.html import escape
# some more imports, but from local files, not django
def update_my_template(request):
user = request.user
# preform some checks for user
...
if request.method == "GET":
updateType = request.GET.get("id")
if updateType:
form = None
if updateType == "something":
form = SomeForm(user)
if updateType == "something else":
form = DifferentForm()
if form is None:
return HttpResponseRedirect("/somepage")
# This was the code that worked in 1.9
rctx = RequestContext(
request, {"form": form, "update": updateType}
)
return render_to_response("mytemplate.html", rctx)
# some different cases, but the error is thrown already
...
这些都不起作用:
dictctx = {"form": form, "update": updateType}
return render(request=request, template_name="mytemplate.html", dictctx)
.
ctx = Context({"form": form, "update": updateType})
return render(request=request, template_name="mytemplate.html", ctx)
.
ctx = Context({"form": form, "update": updateType})
return render(request=request, template_name="mytemplate.html", ctx.flatten())
.
rctx = RequestContext(request, {"form": form, "update": updateType})
return render_to_response("mytemplate.html", rctx.flatten())
【问题讨论】:
-
只是为了确保我的假设是正确的,您可以编辑您的问题并添加您对
Context和render的导入吗? -
当然,一秒钟
-
如果您将
from django.template.context更改为from django.template,我下面的代码是否有效? -
不幸的是,
from django.template.context或from django.template似乎没有任何区别
标签: python django python-2.7 django-templates django-views