William
William

Reputation: 4036

How to use Django template filter in for loop?

How can I filter specific field of a model in template while using for loop.

code:

    {% for news in news_list|position:3 %}

       <img class="d-block w-100 rounded slideimage" style="height:415px" src="{{news.image_link}}" alt="First slide">
                    <h1 class="mb-2">
                      {{news.title}}
                    </h1>
    {% endfor %}

there is a 'position' field in news model,I want to get all the news that position equal 3.I tried

 {% for news in news_list|position:3 %}

any friend can help?

Upvotes: 1

Views: 1302

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477844

You should not filter in your template. Templates should only be concerned with making thinks look nice, not about the content of the things it is rendering. Filtering belongs in the view, since the view is concerned with business logic.

You thus filter with:

def myview(request):
    # …
    news_list = News.objects.filter(position=3)
    # …
    context = {
        'news_list' : news_list
    }
    return render(request, 'my_template.html', context)

Upvotes: 2

Related Questions