【问题标题】:Django - Access Context Dictionary Before TemplateDjango - 在模板之前访问上下文字典
【发布时间】:2012-03-03 22:49:49
【问题描述】:

我希望在实际渲染之前使用上下文处理器或中间件来修改传递给 render_to_response 的字典值。我有一个正在尝试实现的消息传递架构,它将根据我想在呈现模板之前搜索上下文的用户类型的存在来填充消息列表。

例子:

def myview(...):
    ...
    return render_to_response('template.html',
        {'variable': variable},
    )

我希望能够在上下文中添加有关“变量”存在的附加信息。

在我的视图定义它之后但在它到达模板之前如何访问“变量”,以便我可以进一步修改上下文?

【问题讨论】:

  • 如何在视图定义后但在它到达模板之前访问“变量”,以便进一步修改上下文。

标签: django django-middleware django-context


【解决方案1】:

使用TemplateResponse:

from django.template.response import TemplateResponse

def myview(...):
    ...
    return TemplateResponse(request, 'template.html', 
        {'variable': variable},
    )

def my_view_wrapper(...):
    response = my_view(...)
    variable = response.context_data['variable']
    if variable == 'foo':
        response.context_data['variable_is_foo'] = True
    return response

【讨论】:

  • 这是对我的问题的回答 :) 我在中间件中作为 process_template_response() 实现的注释中的函数 my_view_wrapper,然后可以访问 response.context_data,其中包含我需要的数据。谢谢!
【解决方案2】:

这很容易。如果您在示例中只提供了一点更多代码,那么答案可能会让您感到厌烦。

# first build your context, including all of the context_processors in your settings.py
context = RequestContext(request, <some dict values>)
# do something with your Context here
return render_to_response('template.html', context)

更新评论:

render_to_response() 的结果是一个 HTTPResponse 对象,其中包含针对上下文呈现的模板。该对象(据我所知)没有与之关联的上下文。我想您可以将render_to_response() 的结果保存在一个变量中,然后访问您传递给它的上下文,但我不确定您要解决什么问题。

您在渲染期间是否修改上下文?如果是这样,您可能会发现信息不再存在,因为 Context 有一个在模板处理期间推送/弹出的范围堆栈。

【讨论】:

  • 我看不到我的 settings.py 将如何知道在页面加载时正在访问哪种用户类型。我希望根据正在访问的用户类型加载不同的信息,但是这是一个通用操作,因此不需要在每个视图中完成。有没有办法在调用 render_to_response() 之后访问上下文/视图生成的字典?
【解决方案3】:

您可以为上下文创建字典:

def myview(...):
    c = dict()
    c["variable"] = value
    ...
     do some stuff
    ...
    return render_to_response('template.html',c)

也许RequestContext 是您正在寻找的东西。

【讨论】:

  • 在中间件 process_response 中,我使用了 RequestContext(response) 并且它缺少所有视图定义的变量,例如您的响应中的 c["variable"]。另外,如果可能的话,我希望它在视图之外自动执行,因为我将在多个位置加载这些变量。对不起,如果我没有 100% 清楚:)
猜你喜欢
  • 2021-10-17
  • 2021-04-10
  • 2014-02-08
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多