Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type error at ... 'myModel' object is not iterable

67  <h2>Latest Posts</h2>
68  
69  <ul>
70      {% for post in posts %}
71              <li><a href="{{ post.get_absolute_url }}">{{post.title}}</a></li>
72      {% endfor %}
73  </ul>

this is my base template and when i click a post,getting an error at line 70:

TypeError at /blog/posts/indiana-was-dogs-name/
'Blog' object is not iterable

my blog models:

class Blog(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateField(db_index=True, auto_now_add=True)
    category = models.ManyToManyField(Category)


    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/blog/posts/%s/" % self.slug

my index view:

def index(request):

    variables = RequestContext(request, {
                                         'categories': Category.objects.all(),
                                         'posts': Blog.objects.filter(posted__lte=datetime.now()).order_by('-posted', 'title')
                                        })
    return render_to_response('index.html',variables)

there are a few posts about error like this but not including my problem


1 Answers

As it says, the blogs variable you pass to your template is not iterable. You can only iterate through lists and other iterables, and in your case, blogs is a Blog instance, where it should be a QuerySet. You may write, for example

blogs = Blog.objects.all()
return render_to_response(..., {'blogs':blogs,...} ...}

Edit

I would feel more safe if you used the exact syntax given in the Django docs. Maybe the difference of syntax is the culprit, I really don't see yet otherwise.

render_to_response(template_name[, dictionary][, context_instance][, mimetype])

with dictionary set to {'categories': Category.objects.all(), 'posts': Blog.objects.filter(posted__lte=datetime.now()).order_by('-posted', 'title')} and context_instance=RequestContext(request)

like image 110
Steve K Avatar answered Aug 14 '26 14:08

Steve K