You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:如何在{% include %}引入的模板中访问请求数据及上下文变量

Django 子模板访问request与上下文变量的方法

一、访问上下文变量

  • 被{% include %}引入的子模板默认直接继承父模板的所有上下文变量,无需额外配置。比如父模板中存在{{ article_title }},子模板里直接写{{ article_title }}就能调用。
  • 如果需要给子模板传递额外变量,或者覆盖原有变量,可以用with关键字:
    {% include 'sub_tpl.html' with extra_var='自定义值' article_title='新标题' %}
    
  • 注意:如果使用{% include ... only %}语法,子模板将只能访问with中指定的变量,无法继承父模板的其他上下文,谨慎使用。

二、访问request数据

request并非天生在所有模板中都可访问,需要满足两个条件:

  1. 全局配置上下文处理器
    在项目的settings.py中,确保TEMPLATES配置的context_processors列表包含django.template.context_processors.request:
    TEMPLATES = [
        {
            # 其他配置...
            'OPTIONS': {
                'context_processors': [
                    # 其他处理器...
                    'django.template.context_processors.request',
                ],
            },
        },
    ]
    
  2. 父模板能获取request
    只要父模板能正常访问request对象,通过{% include %}引入的子模板就能直接使用{{ request }}及其属性,比如{{ request.user.username }}、{{ request.GET }}。
    如果父模板无法获取request,除了检查上述配置,也可以在视图函数中手动将request传入上下文(但更推荐全局配置上下文处理器的方式):
    from django.shortcuts import render
    
    def my_view(request):
        return render(request, 'base.html', {'request': request})
    

内容的提问来源于stack exchange,提问作者Pycm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:30:57