【问题标题】:Confusion about django.shortcuts.render() method signature in 1.101.10 中关于 django.shortcuts.render() 方法签名的困惑
【发布时间】:2016-08-19 17:41:21
【问题描述】:

Django 1.10 发行说明 (https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10) 说:

  • 删除了以下函数的字典和 context_instance 参数:
    • django.shortcuts.render()
    • ...

但是,1.10 (https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render) 中render() 的文档仍然将context 列为dictionary 类型的参数:

上下文

要添加到模板上下文的值字典。默认情况下,这是一个空字典。如果字典中的值是可调用的,视图将在渲染模板之前调用它。


坦率地说,我的问题是什么?通常这是一个学术问题,但代码如下:

def index(request):
    context = RequestContext(request, {})
    return render(request, 'maintenance/maintenance.html', context) 

产生此错误:

TypeError: dict expected at most 1 arguments, got 3 

这是我能找到的关于问题所在的最佳线索。我还要提一下,这个错误是在将 Django 从 1.8 更新到 1.10 之后出现的。

【问题讨论】:

  • 前 3 个参数的签名没有改变。一个名为context_instance 的可选关键字参数被丢弃。您能否 (1.) 提供完整的回溯,以及 (2.) 确保您的 render 实际上存在 django.shortcuts.render? PS 我认为它会为你创建一个RequestContext
  • 你不需要在大括号内提供一些东西吗?

标签: python django dictionary


【解决方案1】:

您混淆了contextcontext_instance,它们是两个独立的参数。 context_instance 参数已在 Django 1.10 中删除,但 context 仍然存在。

正如文档所说,context 应该是值的字典。您收到错误是因为您传递的是 RequestContext 实例而不是字典。您可以通过将示例视图更改为:

def index(request):
    context = {}
    return render(request, 'maintenance/maintenance.html', context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2013-09-09
    • 2011-01-18
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    相关资源
    最近更新 更多