Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将if station与models字段django一起使用_Python_Django_Django Models_Django Views_Django Templates - Fatal编程技术网

Python 将if station与models字段django一起使用

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

我试图在模板中使用if语句,但它不起作用 在模板中:

{% 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)