Python 将if station与models字段django一起使用
我试图在模板中使用if语句,但它不起作用 在模板中:Python 将if station与models字段django一起使用,python,django,django-models,django-views,django-templates,Python,Django,Django Models,Django Views,Django Templates,我试图在模板中使用if语句,但它不起作用 在模板中: {% for post in posts %} {% if post.tag == 'book' %} <div class="product-item "> <div class="pi-pic "> <img src="{{post.Img.url}} " alt=" "&g
{% for post in posts %}
{% if post.tag == 'book' %}
<div class="product-item ">
<div class="pi-pic ">
<img src="{{post.Img.url}} " alt=" ">
{% if post.tag %}
<div class="sale ">{{post.tag}}</div>
{%endif%}
</div>
</div>
{% endif %}
{%endfor%}
而且
views.py:
def post_list(request):
tags=tags.objects.all()
posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'post/index2.html', {'posts': posts})
由于您的
标记
模型包含\uuuu str\uuuuu
,当仅为了方便而打印对象时,它会给出一个字符串值。因此,您将post.tag
实例与字符串book
进行比较。这就是为什么if
块不能按预期工作的原因。因此,与tag\u name
属性相比,该属性将起作用:
{% for post in posts %}
{% if post.tag.tag_name == 'book' %}
<div class="product-item ">
<div class="pi-pic">
<img src="{{post.Img.url}}" alt="">
{% if post.tag %}
<div class="sale">{{post.tag}}</div>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
{%for posts in posts%}
{%if post.tag.tag_name=='book%}
{%if post.tag%}
{{post.tag}
{%endif%}
{%endif%}
{%endfor%}
post.tag是一个对象而不是一个字符串book
,我想您需要将它更改为
{%if post.tag和post.tag.tag_name=='book'%}
或者将方法get\u tag\u string
添加到您的Post
模型中
def get_tag_string(self):
return str(self.tag)
然后,如果post.get\u tag\u string=='book'%}
然后你不需要第二个if,它将始终是
True
如果第一个if是True
看起来你还没有结束你的第一个如果在这里粘贴代码是个问题,主代码是OK的,我已经编辑好了,检查你的块是否匹配。另外,请添加您的视图.py
非常感谢,但它不起作用。。。这是行不通的。我刚刚编辑了你的帖子。您的工作是查看模板是否与当前代码匹配。另外,要为该模板添加views.py
,是否确实存在标记string
?如果添加方法get\u tag\u string
,我的代码与此处发布的代码完全相同。在它的开头添加print(self.tag)
,你会看到你有什么标签标签簿真的存在吗?我甚至可以使用{{post.tag}并查看它,但我不知道if语句有什么问题它可能是'book'
,'book'
,'book'
,'book'
,'book'
,检查一下你有什么你确定你正确地按照我说的做了吗<代码>post.tag.tag\u名称
是。例如,此{%if post.tag.tag_name=='book'%}您是否可以确保您的tag_name是否有book
?非常感谢是的,问题是多了一个空间
def get_tag_string(self):
return str(self.tag)