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

如何在Django中记录缺失模板变量并显示位置与上下文

Django模板缺失变量日志优化与调试配置方案

自定义日志过滤器(解决无关日志、调试模式抛异常)

创建项目根目录下的logging.py文件,实现过滤无效日志、调试模式主动抛出异常的逻辑:

import logging
from django.conf import settings
from django.template.base import TemplateSyntaxError, VariableDoesNotExist


class TemplateMissingVariableFilter(logging.Filter):
    def filter(self, record):
        msg = record.getMessage()
        # 过滤掉exception_notes相关的无效日志
        if 'exception_notes' in msg:
            return False
        
        # 仅保留模板变量缺失的核心日志
        if 'Undefined variable' not in msg:
            return False
        
        # DEBUG模式下直接抛出异常,终止页面加载
        if settings.DEBUG:
            var_name = msg.split("'")[1]
            template_loc = msg.split("in template")[-1].strip()
            raise TemplateSyntaxError(f"Missing variable '{var_name}' in {template_loc}")
        
        return True


# Patch Django的异常类,让日志能携带模板上下文
original_var_init = VariableDoesNotExist.__init__
def patched_var_init(self, *args, **kwargs):
    original_var_init(self, *args, **kwargs)
    if 'context' in kwargs:
        self.context = kwargs['context']

VariableDoesNotExist.__init__ = patched_var_init

自定义日志格式化器(精简输出、展示关键信息)

在同一个logging.py中添加格式化器,只输出核心内容:

class TemplateMissingVariableFormatter(logging.Formatter):
    def format(self, record):
        msg = record.getMessage()
        # 提取变量名和模板位置
        var_name = msg.split("'")[1]
        template_loc = msg.split("in template")[-1].strip()
        
        # 从异常信息中提取模板上下文
        context = "No context available"
        if record.exc_info:
            exc = record.exc_info[1]
            if isinstance(exc, VariableDoesNotExist) and hasattr(exc, 'context'):
                # 展平上下文字典,方便查看
                context = str(exc.context.flatten())
        
        # 构建简洁日志行
        return f"[TEMPLATE ERROR] Missing var: '{var_name}' | Location: {template_loc} | Context: {context}"

配置settings.py中的日志系统

将自定义过滤器和格式化器接入Django日志配置:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'template_missing_var': {
            '()': 'your_project_name.logging.TemplateMissingVariableFilter',
        },
    },
    'formatters': {
        'template_error': {
            '()': 'your_project_name.logging.TemplateMissingVariableFormatter',
        },
    },
    'handlers': {
        'template_errors': {
            'level': 'WARNING',
            'filters': ['template_missing_var'],
            'class': 'logging.StreamHandler',
            'formatter': 'template_error',
        },
    },
    'loggers': {
        'django.template': {
            'handlers': ['template_errors'],
            'level': 'WARNING',
            'propagate': False,  # 阻止日志向上传播,避免冗余输出
        },
    },
}

关键效果说明

  • 过滤无效日志:直接排除exception_notes相关的无关条目
  • 精简输出:自定义格式化器只保留变量名、模板位置、上下文三个核心信息
  • DEBUG模式中断加载:调试环境下主动抛出异常,页面直接加载失败
  • 上下文展示:通过patch异常类,实现模板传入上下文的输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:33:01