【问题标题】:django request in template模板中的 django 请求
【发布时间】:2023-09-17 19:33:01
【问题描述】:

我已启用 django 请求处理器

TEMPLATE_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)

我仍然不必请求模板中可用的变量。 我必须手动传递它。使用 django 1.0.2 网络上的任何地方似乎都只是关于启用的请求处理器..

我也将 RequestContext 用作:

 return render_to_response(
    'profile.html',
    {
        'persons':Person.objects.all(),
        'person':Person.objects.get(id=id),
         'request':request,
    },
    context_instance=RequestContext(request)
)

运气不好

天啊 它的新名称是 TEMPLATE_CONTEXT_PROCESSORS

【问题讨论】:

  • 为什么要让模板知道有关请求的任何信息?
  • easy : 我需要知道动态导航请求的路径 URL。我完成了它现在可以工作了。

标签: django request processor


【解决方案1】:

settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
  # ...
  'django.core.context_processors.request',
  # ...
)

【讨论】:

【解决方案2】:

TEMPLATE_CONTEXT_PROCESSORS 代替 TEMPLATE_PROCESSORS

【讨论】:

  • 感谢您编辑原始问题,尽管进一步的更新使this answersettings.py 中的内容更加准确。
【解决方案3】:

请注意,从 Django 1.8 开始,这已更改为“模板”设置,并且在默认配置中,不包括请求处理器。

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        # insert your TEMPLATE_DIRS here
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
            # list if you haven't customized them:
            'django.contrib.auth.context_processors.auth',
            'django.template.context_processors.debug',
            'django.template.context_processors.i18n',
            'django.template.context_processors.media',
            'django.template.context_processors.static',
            'django.template.context_processors.tz',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},]

只需重新添加请求处理器即可解决问题:

'django.core.context_processors.request',

有关详细信息,请参阅Django Upgrading Docs

【讨论】:

【解决方案4】:

您确定没有可用于模板的request 变量吗?删除线后会发生什么

'request':request,

这与该行存在时不同。如果您的模板加载方式相同,则问题出在您的模板上。

【讨论】:

  • 对我来说,处理请求和更新上下文的函数在没有请求的情况下传递了上下文。请求丢失了,所以必须先手动将其传递给函数,因为与 render() 不同,传递请求也不聪明。与此答案有些相关。
【解决方案5】:

MIDDLEWARE_CLASSES=( ... 'yourfolder.yourfile.yourclass', ... 你的班级:

类 AddRequestToTemplate: process_templaet_response(自我,请求,响应): response.context_data['request']=request

【讨论】: