【发布时间】:2017-12-23 05:48:16
【问题描述】:
所以我做了一些搜索,但找不到我的特定问题的答案...发生的事情是:
我有一个名为 section 的模型,其中包含 section_title 字段。该字段可以有空格,例如:“First Section”。
当我将它传递给 Django 时,我正在使用 replace() 删除 Python 中的空格,并在 Django 上创建了一个过滤器,它也像这样删除了空格:
@register.filter(name='replace_char')
def replace_char(value, arg):
return value.replace(arg, '')
然后在我的模板上:
{% for subsection in section.section_title|replace_char:" " %}
问题是 subsection 显示为 section_title 中的每个字符,而不是 section_title 引用的列表。这是传递给模板的字典:
{'sections': [, ], 'FirstSection': [,
如果我硬编码:
{% for subsection in FirstSection %}
它有效...
有什么想法吗?谢谢!
OBS:我删除了空格,因为我认为它们会导致问题,但显然不是。它也不适用于空间......
完整模板代码:
{% for section in sections %}
<div class="sectionHeader">
{{ section.section_title }}
</div>
<div class="forumSection">
{% for subsection in section.section_title|replace_char:" " %}
<div>
{{ subsection }}
</div>
{% endfor %}
</div>
{% endfor %}
型号:
class Section(models.Model):
def __str__(self):
return self.section_title
section_title = models.CharField(primary_key = True, unique = True, max_length = 50)
class Subsection(models.Model):
def __str__(self):
return self.subsection_title
subsection_title = models.CharField(max_length = 50)
subsection_section = models.ForeignKey(
'Section',
on_delete = models.CASCADE,
)
【问题讨论】:
-
我相信你所关注的是唯一的解决方案。
-
@AnupYadav,对不起,我没明白你的意思。
-
你能显示从你的视图传递的上下文变量吗?
-
传递给模板的字典不包含“部分”。您指的是“部分”吗?
-
@UmarAsghar,在我的第一条评论中,上下文变量不是以粗体显示的吗?
标签: python html django templates