views:

31

answers:

3

For example If I have the following models, views and code in a template...

class news(models.Model):
    type = models.ForeignKey(----)  (charfield)
    title = models.CharField(max_length=100)
    published = models.DateTimeField(default=datetime.now)
    summary = models.CharField(max_length=200)

def ----():
    items = news.objects.all().order_by('-published')[:5]
    return {'items': items}

{% if items %}
<ul>
{% for item in items|slice:":2" %}
<li>{{ item.title }}</li>
<li>{{ item.summary }}</li>
{% endfor %}
<ul>
{% endif %}

How would you go about displaying items only of a certain type. using the above template code.

e.g. display all items of only type = Worldnews.

I know this is usually achieved in views however I would like to know how this is achieved inside a template.

All help is greatly appreciated.

+1  A: 

Trying to achieve it in a template is a very bad idea. Is is also not possible.

The whole idea of templates is to separate logic from presentation. The Django creators designed templates for only very simple presentation stuff to be possible, so as far as I know that is impossible.

EDIT: It's not really impossible, but not exactly easy and not a very good idea. See the comments.

alpha123
It's not *impossible*, in that you can do it with a custom template tag or filter. But you're right to say it's a bad idea.
Daniel Roseman
Oh, I didn't think of that.
alpha123
You're correct it is a bad idea however, Custom template tags look the best way if need be. But I guess taking the functionality out of views and into templates defeats the purpose of django a little, still I was curious to know. Thanks.
Rick
A: 
news.objects.get(type__exact="Worldnews")

EDIT: Use the above for the type that you need for that view.

Andrew Sledge
The OP specifically asked that he wanted to do this within the template.
Daniel Roseman
@Daniel - Don't encourage bad behavior.
Andrew Sledge
A: 

Am I missing something, this seems easy:

{% if items %}
<ul>
{% for item in items %}
    {% ifequal item.type "Worldnews" %}
        <li>{{ item.title }}</li>
        <li>{{ item.summary }}</li>
    {% endifequal %}
{% endfor %}
<ul>
{% endif %}

As others have said, this is much better done in the view function.

Ned Batchelder
Maybe I am the one missing something? This doesn't seem to work?
Rick
When you find yourself saying something doesn't work, you should *always* describe what it *is* doing, that way others can help you.
Ned Batchelder