gpt4 book ai didi

python - Django string_if_invalid 和默认值

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:35 25 4
gpt4 key购买 nike

我在 Django 模板设置中将 string_if_invalid 设置为“INVALID”。还有一些模板看起来像这样:

{{ some_nonexisting_value|default:'Default value' }}

渲染后的结果看起来像'INVALID'。因此,不使用默认值。有什么方法可以使 string_if_invalid 在不更改模板的情况下使用默认值?

编辑:模板设置如下所示:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'OPTIONS': {
'libraries': {
'utm_tags': 'kurator.templatetags.utm_tags',
},
'string_if_invalid': 'INVALID',
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'kurator.context_processors.static_hash',
'kurator.context_processors.debug',
]
},
},
]

最佳答案

不,不可能让 default 过滤器显示提供的默认值而不是无效字符串。

请注意 the docs警告不要使用 string_if_invalid 选项:

For debug purposes only!

While string_if_invalid can be a useful debugging tool, it is a bad idea to turn it on as a ‘development default’.

Many templates, including those in the Admin site, rely upon the silence of the template system when a non-existent variable is encountered. If you assign a value other than '' to string_if_invalid, you will experience rendering problems with these templates and sites.

Generally, string_if_invalid should only be enabled in order to debug a specific template problem, then cleared once debugging is complete.

对于您自己的模板,我想您可以编写自己的模板标签,它采用变量名和默认值,然后尝试从模板上下文中获取变量。但是,这并不能解决其他使用常规 default 过滤器的模板中的问题,包括 Django admin。

关于python - Django string_if_invalid 和默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com