【问题标题】:How to throw exception if input params is invalid in Django Template如果输入参数在 Django 模板中无效,如何抛出异常
【发布时间】:2026-01-24 05:30:02
【问题描述】:

如果模板输入参数无效,有没有办法抛出异常?在 django 旧版本中,我们可以像下面的代码那样做。但是最新的 django 版本呢? 有一个设置 string_if_invalid = 'string' 的选项,但我们需要为此抛出异常的唯一原因是我们显然不希望邮件服务器向客户发送垃圾邮件。

谢谢。

# settings.py in old versions
class InvalidVarException(object):
    def __mod__(self, missing):
        try:
            missing_str=unicode(missing)
        except:
            missing_str='Failed to create string representation'
        raise Exception('Unknown template variable %r %s' % (missing, missing_str))
    def __contains__(self, search):
        if search=='%s':
            return True
        return False

TEMPLATE_DEBUG=True
TEMPLATE_STRING_IF_INVALID = InvalidVarException()

【问题讨论】:

    标签: python django templates configuration


    【解决方案1】:

    在 Django 中
    TEMPLATE_STRING_IF_INVALID = 'DEBUG WARNING: undefined template variable [%s] not found'
    

    在您的 settings.py 中。

    在 Django 中>=1.10

    string_if_invalid = 'DEBUG WARNING: undefined template variable [%s] not found'
    

    Also check this link about invalid template variables

    And this link about django backend template engine

    【讨论】:

    • 没关系,如果你找到解决办法请在此贴出来
    【解决方案2】:

    【讨论】: