gpt4 book ai didi

python - 如何从 Django 模板中访问包含连字符的字典键?

转载 作者:太空狗 更新时间:2023-10-29 20:16:11 24 4
gpt4 key购买 nike

我们有一个建立在自定义数据库上的系统,其中许多属性的命名都包含连字符,即:

user-name
phone-number

这些属性不能在模板中访问,如下所示:

{{ user-name }}

Django 为此抛出异常。我想避免将所有键(和子表键)转换为使用下划线来解决这个问题。有没有更简单的方法?

最佳答案

如果您不想重构您的对象,自定义模板标签可能是唯一的选择。要使用任意字符串键访问字典,this question 的答案提供了一个很好的例子。

对于懒惰的人:

from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
# Try to fetch from the dict, and if it's not found return an empty string.
return the_dict.get(key, '')

你这样使用:

{% dictKeyLookup your_dict_passed_into_context "phone-number" %}

如果您想使用任意字符串名称访问对象的属性,您可以使用以下方法:

from django import template
register = template.Library()

@register.simple_tag
def attributeLookup(the_object, attribute_name):
# Try to fetch from the object, and if it's not found return None.
return getattr(the_object, attribute_name, None)

你会这样使用:

{% attributeLookup your_object_passed_into_context "phone-number" %}

您甚至可以为子属性想出某种字符串分隔符(如“__”),但我会把它留给作业:-)

关于python - 如何从 Django 模板中访问包含连字符的字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252387/

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