我正在用 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 %}
輸出
(空的)
預期的
云風
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])
uj5u.com熱心網友回復:
試試這個。在 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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352975.html
上一篇:如何在DRF中對串列進行排序?
