如何检查表对象中字段的值是否等于 django 模板语言中的特定字符串?

Ideas.我正在迭代 django 表中名为表中一个字段 is的所有条目status,并且我想检查状态是否等于某个特定字符串。在我的例子中,我已经检查过我是否正确访问了该字段idea.status,但我找不到如何将该条目与 django 模板语言文档中的特定字符串进行比较。我正在尝试根据该单元格中的内容更改表格的单元格颜色。这是我尝试过的,但没有成功:


{% for idea in ideas_list %}

...

        {% if idea.status == 'Not Started' %}

        <td style="background-color:red;">

        {% elif idea.status == 'Completed' %}

        <td style="background-color:green;">

        {% elif idea.status == 'In Progress' %}

        <td style="background-color:yellow;">

        {% else %}

        <td>

        {% endif %}

            {{idea.status}} &nbsp;</td>

...

{% endfor %}

我的页面仍在使用表中的状态文本进行渲染,这向我表明所有 if 都失败了,这将导致满足 else 条件,给出<td>{{idea.status}} &nbsp;</td>, 没有单元格颜色,并向我表明问题出在我的 if 中陈述本身。


达令说
浏览 61回答 2
2回答

犯罪嫌疑人X

我找到了一个有效的答案,并表明它与 djnago 使用的字符串格式有关。我使用了 slugify 过滤器,它将字符串转换为特定格式(小写、破折号而不是空格),然后更改我的 if 条件以匹配该格式,并且它起作用了。{% for idea in ideas_list %}...&nbsp; &nbsp; &nbsp; &nbsp; <td>{{idea.priority}} &nbsp;</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>{{idea.difficulty}} &nbsp;</td>&nbsp; &nbsp; &nbsp; &nbsp; {% if idea.status|slugify == 'not-started' %}&nbsp; &nbsp; &nbsp; &nbsp; <td style="background-color:red;">&nbsp; &nbsp; &nbsp; &nbsp; {% elif idea.status|slugify&nbsp; == 'completed' %}&nbsp; &nbsp; &nbsp; &nbsp; <td style="background-color:green;">&nbsp; &nbsp; &nbsp; &nbsp; {% elif idea.status|slugify&nbsp; == 'in-progress' %}&nbsp; &nbsp; &nbsp; &nbsp; <td style="background-color:yellow;">&nbsp; &nbsp; &nbsp; &nbsp; {% else %}&nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; {% endif %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{idea.status}} &nbsp;</td>...{% endfor %}您可以在此处查看 django 如何使用 slugify 格式化字符串: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/

繁星淼淼

您的模板部分是正确的。这是正确的语法:{% if idea.status == 'Not Started' %}记录数据调试模板中的内容的最简单方法是在渲染模板之前记录您所拥有的内容。您可以使用日志记录模块Docs或简单的:print(payload_for_rendering)Django 调试工具栏为每个 Django 开发人员安装主要调试工具 - Django 调试工具栏安装文档。您可以使用工具栏中的“模板”模块在漂亮的用户界面中查看模板收到的数据。您可以检查是否向模板渲染发送了正确的数据。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python