【问题标题】:Django Template tag in {% if %} block does not show{% if %} 块中的 Django 模板标签不显示
【发布时间】:2021-12-20 14:30:03
【问题描述】:

我正在用 Django 制作公告板。

如何用我想要的字母而不是类型编号来表达它? my bulletin board

HTML 模板(board.html)

{% for p in postlist %}
    <tr>
        <td>
            {% if p.p_type == '1' %}
            'cloud'
            {% elif p.p_type == '2' %}
            'wind'
            {% endif %}
        </td>
    </tr>
{% endfor %}

输出

(空)

预期

云风

Vies.py

def board(request, p_type=None):
    current_type = None
    p_types = PostType.objects.all()
    postlist = Post.objects.all()

    page = request.GET.get('page', '1')
    if p_type:
        current_type = get_object_or_404(PostType, p_type=p_type)
        postlist = postlist.filter(p_type=current_type)

    paginator = Paginator(postlist, 10)  # Showing 20 posts.
    page_obj = paginator.get_page(page)

    return render(request, 'board/board.html', {'current_type':current_type, 'p_types': p_types, 'postlist': page_obj})

模型.py

class PostType(models.Model):
p_type = models.CharField(max_length=200, db_index=True)

def __str__(self):
    return self.p_type

def get_ptype_url(self):
    return reverse('board:board', args=[self.p_type])

【问题讨论】:

  • 向我们展示您的PostType 型号!

标签: python django web django-templates


【解决方案1】:

试试这个。在 django 中,当您创建外键时,它将为数据库添加 _id,因此现在在您的模板中,您可以使用此 id(p_type_id) 进行比较,并且您应该确保 Cloud 有 pk =1,Wind 的 pk=2。

{% for p in postlist %}
    <tr>
        <td>
            {% if p.p_type_id == 1 %}
                'cloud'
                {% elif p.p_type_id == 2 %}
                'wind'
                {% endif %}
            </td>
        </tr>
    {% endfor %}

【讨论】:

  • 非常感谢您告诉我!你的经历很突出。
  • 我真的很好奇。谢谢你告诉我。
  • @stand0 我很高兴能够帮助你。快乐的编码)。
猜你喜欢
  • 1970-01-01
  • 2018-09-03
  • 2018-10-21
  • 2011-11-02
  • 2011-05-14
  • 2019-06-16
  • 2016-05-18
  • 1970-01-01
  • 2011-02-09
相关资源
最近更新 更多