Talal Alsarrani
Talal Alsarrani

Reputation: 5

List doesn't load in django templates

So i'm trying to filter my model in this way in views.py:

news_list = list(models.Entry.objects.filter(category='news'))

and the problem is that the list cant be accessable from the django templates. this is the way I'm trying to access it in home.html:

{% for news in news_list %}

{{ news.title }}

{% endfor %}

and this:

{{ news_list.0.title }}

I'm sure the way that I created the list is right beauce when I loop through the list in the views.py it show up in the terminal.

I'm using python3.3 and django 1.8.3

views.py :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views import generic
from . import models
from blog.models import Entry


class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "home.html"
    paginate_by = 3
    news_list = Entry.objects.filter(category='news')
    i = 0
    for x in news_list:
        i = i+1
        print(x.title,i)

Upvotes: 0

Views: 404

Answers (3)

Piotr Pęczek
Piotr Pęczek

Reputation: 408

That's because in django you don't access lists, but querysets. Try:

context['news_list'] = Entry.objects.filter(category='news')

Upvotes: 0

Rahul Gupta
Rahul Gupta

Reputation: 47846

You are trying to access news_list in the template when it is infact not present in the template.

You need to pass news_list in the context data. Override the get_context_data() and pass this variable.

class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "home.html"
    paginate_by = 3

    def get_context_data(self, **kwargs):
        context = super(BlogIndex, self).get_context_data(**kwargs)
        context['news_list'] = Entry.objects.filter(category='news') # pass 'news_list' in the context
        return context

Then in your template, you can use the normal for loop.

{% for news in news_list %}

    {{ news.title }}

{% endfor %} 

Note: You don't need to convert the QuerySet to a list as it is already an iterable.

Upvotes: 2

Sreekanth Reddy
Sreekanth Reddy

Reputation: 483

The queryset result can be used to iterate in django template. So there is no need to convert query set object into list. List is not iterable in django template though python does. You can use django-mptt is a premade solution, which should fit your problem quite good.

Upvotes: 0

Related Questions