seagull 13
seagull 13

Reputation: 35

Using if statment with models field django

I'm trying to use if statement in the template but it doesn't work in template:

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

models.py

class Post(models.Model):
    title = models.CharField(max_length=200,null=True)
    Img = models.ImageField(upload_to='images/',null =True) 
    tag=models.ForeignKey('tags',on_delete=models.CASCADE, null=True)
class tags(models.Model):
    tag_name= models.CharField(max_length=100)
    def __str__(self):
        return self.tag_name

and in 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})

Upvotes: 0

Views: 58

Answers (2)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

As your tags model contains __str__ which is giving a string value, when object is printed just for the sake of easiness. So, your comparision of post.tag instance is with string, book. That's why your if block was not working as expected. So, comparing with tag_name attribute will work:

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

Upvotes: 1

Andrey Maslov
Andrey Maslov

Reputation: 1466

post.tag is an object not a string book, i think you need to change it to {% if post.tag and post.tag.tag_name == 'book' %} or add method get_tag_string to your Post model

def get_tag_string(self):
    return str(self.tag)

and then you can check {% if post.get_tag_string == 'book' %}

and then you don't need second if, it will always be True if first one is True

Upvotes: 0

Related Questions