python - {{ 请求 }} var 空

标签 python django templates request render-to-response

我正在运行 Django 1.9.6 如果我尝试在模板中使用 {{ request.path }} ,则 var/tag 为空

这是我的设置.py

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        os.path.join(BASE_DIR, '_templates'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'django.template.context_processors.i18n',
        ],
        'builtins': ['django.templatetags.i18n']
    },
},

]

我读到,在 1.8 版本之后,您只需要包含 'django.template.context_processors.request' ,您就会在模板中运行 var

如果在我的 View 中添加,我就能解决该问题

return render_to_response('admin-users/events.html', {}, context_instance=RequestContext(request))

我做错了什么,因为我读了很多答案,都说我不必添加 RequestContext

最佳答案

请改用 render 方法,它会自动使用 RequestContext 来呈现模板。

 return render(request, 'admin-users/events.html', {}) 

不再推荐使用 render_to_response 快捷方式。

关于python - {{ 请求 }} var 空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596690/

相关文章:

python - Matplotlib PatchCollection 与 set_array : how to match face-color with edge-color?

c++ - 无法使用默认参数初始化 lambda 成员变量

django - 将数据生产者作为工作人员集成到 Django Channels 2.x

python - 无法在 Django 模板 html 中使用过滤器

django - Virtualenv "workon"命令在一个终端选项卡中在线工作。

c++ - 尽管已声明,但找不到模板化函数

c++ - 为什么在使用我的 auto_ptr 样式类访问结构成员时得到 'unidentified identifier'?

python - 比丘达; nvcc 致命 : Visual Studio configuration file '(null)' could not be found

python - 使用 DBSCAN 聚类 word2vec 输出的故障排除技巧

带有语句 : 'Syntax error: invalid syntax' 的 Python