Pagination Returning the Wrong Object (not iterable?)
I am trying to return paginated objects and then iterate through them. Seems pretty straightforward. Apparently I'm missing something, though. Can you spot the error?
The view:
def thumbnails(request):
page = request.GET.get('page', 1)
album = request.GET.get('a', None )
if (album):
objects = Album_Photos.objects.filter(id=album)
else:
objects = None
if (objects):
paginator = Paginator(objects, 25)
try:
photos = paginator.page(page)
except PageNotAnInteger:
photos = paginator.page(1)
except EmptyPage:
photos = None #paginator.page(paginator.num_pages)
return render_to_response('p开发者_如何学JAVAhotos/thumbnails.html', {'photos': photos}, context_instance = RequestContext(request))
The template:
{% if photos %}
{% for photo in photos %}
<img src="{{photo.original.url}}">
{% endfor %}
{%endif%}
The error:
TemplateSyntaxError at /photos/thumbnails/
Caught TypeError while rendering: 'Page' object is not iterable
1 {% if photos %}
2 {% for photo in photos %}
3 <img src="{{photo.original.url}}">
4 {% endfor %}
5 {%endif%}
Well, unlike the example in the Django docs (at least in my case), you must append .object_list to that Page
object.
{% if photos %}
{% for photo in photos.object_list %}
<img src="{{photo.original.url}}">
{% endfor %}
{%endif%}
This has been changed in django: somewhere between version 1.3 and 1.6, Paginator.Page has been made iterable.
If you follow the example from the current documentation, while using an older version of django, you get this error.
Either append .object_list as Brian D. said, or upgrade django.
精彩评论