开发者

How do you display only specific variable information within a django-template?

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&g开发者_StackOverflow社区t;{{ 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.


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.


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.


news.objects.get(type__exact="Worldnews")

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜