ramono
ramono

Reputation: 462

Django if tag doesn't work here

I have a blog app and i want to show each post in a very different way using classes and showing/not-showing parts, based in a foreign key value "postype". This is my code:

{% for post in posts.object_list %}
    <div class="{{ post.postype }}">
        <h4>{{ post.title }}</h4>
        {% if post.postype == 'Post' %}<p>{{ post.created }}</p>{% endif %}
    </div>
{% endfor %}

And the result of that is:

<div class="Post">
    Title Post One
</div>
<div class="News">
    Title Post Two
</div>
<div class="Post">
    Title Post Three
</div>

So my question is, why the "post.created" is not showing even though the div class shows "Post" in two cases?, which means the if should match.

This is the model i'm using

class Postype(models.Model):
    postype = models.CharField(max_length=32)

    def __unicode__(self):
        return self.postype

class Post(models.Model):
    author = models.ForeignKey(User)
    postype = models.ForeignKey(Postype)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    text = models.TextField()
    allow_comments = models.BooleanField(db_index=True, default=True)
    published = models.BooleanField(db_index=True, default=True)

    objects = PostManager()

    def __unicode__(self):
    return u"%s - %s" % (self.title, self.created) 

    def save(self, *args, **kwargs):
        self.slug = slughifi(self.title)
        super(Post, self).save(*args, **kwargs)

Thanks

Upvotes: 2

Views: 146

Answers (2)

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

If post.posttype is a foreign key to another model, you need to specify what attribute of posttype you want to compare against

so if

class PostType(models.Model):
    name = models.CharField(...)

you should have

{% if post.posttype.name == "Post" %}...{% endif %}

As it stands you are comparing an object (posttype) to a string ("Post") which will always fail.

The reason the div shows the class "Post" correctly, is because django is automatically guessing how to display the Post model when you don't specify a field. To change the way a post is printed when no attribute is given, you can overwrite the unicode method of the model:

class PostType(models.Model):
    name = models.CharField(...)

    def __unicode__(self):
        return self.name

This means that when you reference this post type (like in your question as ) the unicode method is called which returns self.name

Upvotes: 3

tlunter
tlunter

Reputation: 724

Have you tried double quotes instead of single quotes in the if statement?

Upvotes: 0

Related Questions