python - {% if %} 块中的 Django 模板标签不显示
问题描述
我正在用 Django 制作一个公告板。
如何用我想要的字母而不是类型号来表达它?我的公告板
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 %}
输出
(空的)
预期的
云风
维斯.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])
解决方案
试试这个。在 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 %}
推荐阅读
- sql - 无法将 BLOB 数据插入表中
- c++ - 特征:vector3ds之间的快速平均角度
- google-maps - 使用 Google Place Autocomplete API 设置 componentRestrictions
- python - 为什么未检测到全局标志?
- git - 我无法连接到 bitbucket,不是通过 ssh 也不是通过 https
- python - for循环中的字节到字符串错误
- c++ - Visual Hull C++ 和行进立方体
- python - Google Cloud Dataflow:在 GroupByKey 之后写入 BigQuery 会导致延迟,但 CoGroupByKey 不会。为什么?
- c++ - void* 数组将元素转换为另一种类型
- javascript - 使用 S3 将 JSON 文件放入 AWS 存储桶