【问题标题】:Pagination Returning the Wrong Object (not iterable?)分页返回错误的对象(不可迭代?)
【发布时间】:2011-10-04 23:15:22
【问题描述】:

我正在尝试返回分页对象,然后遍历它们。看起来很简单。不过,显然我错过了一些东西。你能发现错误吗?

观点:

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('photos/thumbnails.html', {'photos': photos}, context_instance = RequestContext(request))

模板:

{% if photos %}
    {% for photo in photos %}
        <img src="{{photo.original.url}}">
    {% endfor %}
{%endif%}

错误:

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%}

【问题讨论】:

    标签: django pagination


    【解决方案1】:

    嗯,与 Django 文档中的示例不同(至少在我的情况下),您必须将 .object_list 附加到该 Page 对象。

    {% if photos %}
        {% for photo in photos.object_list %}
            <img src="{{photo.original.url}}">
        {% endfor %}
    {%endif%}
    

    【讨论】:

    【解决方案2】:

    这已在 django 中进行了更改:在 1.3 和 1.6 版本之间的某个地方,Paginator.Page 已成为可迭代的。

    如果您遵循当前文档中的示例,在使用旧版本的 django 时,您会收到此错误。

    按照 Brian D. 所说的那样附加 .object_list,或者升级 django。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 2016-09-11
      • 2019-01-12
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      相关资源
      最近更新 更多