从RequestContext获取当前请求?

时间:2011-10-04 04:56:52

标签: django

Django RequestContext是否有办法获取与之关联的HttpRequest对象?是否有像get_request()之类的方法来获取传递给构造函数的request?我需要从一个只接收RequestContext的方法中引用它。

2 个答案:

答案 0 :(得分:10)

'django.core.context_processors.request'添加到TEMPLATE_CONTEXT_PROCESSORS设置。并使用以下方式获取上下文可用的请求:

request = context['request']

答案 1 :(得分:1)

不,django.template.RequestContext(住在django/template/context.py中)不存储对请求对象的任何引用:

class RequestContext(Context):
    """
    This subclass of template.Context automatically populates itself using
    the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
    Additional processors can be specified as a list of callables
    using the "processors" keyword argument.
    """
    def __init__(self, request, dict=None, processors=None, current_app=None, use_l10n=None):
        Context.__init__(self, dict, current_app=current_app, use_l10n=use_l10n)
        if processors is None:
            processors = ()
        else:
            processors = tuple(processors)
        for processor in get_standard_processors() + processors:
            self.update(processor(request))

如果修补了Django在构造函数中包含这样的简单行:

self.request = request

和这样的函数定义:

def get_request(self):
     return self.request
那时我们会做生意。不幸的是,我们不是,所以答案是“不,你不能得到与RequestContext相关联的请求对象。”

相关问题