【问题标题】:Django on Apache web server 'dict' object has no attribute 'render_context'Apache Web 服务器“dict”对象上的 Django 没有属性“render_context”
【发布时间】:2026-02-05 00:50:02
【问题描述】:

我遇到了一点问题,我将我的 Django 项目上传到了一个运行 apache、mod_python 和 django 的网络服务器。在我开发的计算机上,以下工作正常

nameBox = getNamesBox().render(locals())

-

def getNamesBox():
    users = User.objects.filter()

    templateString = '<select name="name box">'
    for user in users:
        templateString += '<option value="' + user.name + '"> ' + user.name + '</option>'

    templateString += '</select>'

    template = Template(templateString)

    return template

但在 web 服务器上,当从 apache 或 manage.py runserver 运行时,它会说

AttributeError at /order_site/order/
'dict' object has no attribute 'render_context'

两台机器上的代码是相同的,所以我觉得可能是其他问题?它无法呈现我的表单,我不知道为什么。

【问题讨论】:

  • 您似乎错过了模板的全部意义。为什么要使用连接手动创建文本,然后“渲染”不包含模板语法的内容,而不是实际使用具有适当模板逻辑的模板文件来为您完成所有这些工作?
  • 或者,更好的是,使用表单类。
  • @Rafe 好吧,是的,确实。

标签: python html django apache mod-python


【解决方案1】:

Template 上的 render() 方法将 Context 对象作为其参数,而不是字典。您必须从 dict 构造一个 Context 对象,例如

namedbox = getNamesBox().render(Context(locals()))

【讨论】:

  • 可以用from django.template import Context导入
  • 在较新的版本中render() 将字典作为没有此方法的上下文
  • @patroqueeet 我也有人这么说。但是我已经看到了 Django 1.11 的Template,render() 实现。它在那里尝试访问传递的 dict 对象的 render_context 属性。在我的情况下,当我传递一个 dict 对象时它引发了一个错误。它说,“dict object has no attribute 'render_context'。”