简体   繁体   English

根据字母(AZ)分页

[英]Paginating based on the alphabet (A-Z)

I have a simple contacts application where I want to paginate the contact list based on first name alphabet. 我有一个简单的联系人应用程序,我想根据名字字母对联系人列表进行分页。

Here is my views.py 这是我的views.py

def contacts(request):
    contact_list = Contact.objects.filter(user=request.user).order_by('first_name')
    pages = [contact_list.filter(first_name__istartswith=i) for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
    return render(request, 'contact/contact.html', {'contact_list': contact_list, 'pages': pages})

Here is my template 这是我的模板

{% for alphabet in pages %}
{% if alphabet %}
    <p>{{ alphabet }}</p>
    {% for contact in contact_list %}
    {% if contact in pages %}
    <ul>
        <li><a href="/contacts/{{ contact.id }}/">{{ contact.first_name }}</a></li>
    </ul>
    {% endif %}
    {% endfor %}
{% endif %}
{% endfor %}

The output from this is something like 这样的输出是这样的

[<Contact: Steve>, <Contact: Su>]

Steve

Su

[<Contact: Ted>]

Ted

[<Contact: Zedd>]

Zedd

The {{ alphabet }} prints a list. {{ alphabet }}打印一个列表。 What should I write to print the alphabet instead? 我应该写些什么来打印字母?

Capture the alphabet in the context variable: 捕获上下文变量中的字母:

pages = [{"letter": i, "contacts": contact_list.filter(first_name__istartswith=i) } 
           for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
return render(request, 'contact/contact.html', {'pages': pages})   # why pass contact_list?

Your template should be simplified to: 您的模板应简化为:

{% for alphabet in pages %}
  {% if alphabet.contacts %}
    <p>{{ alphabet.letter }}</p>
    {% for contact in alphabet.contacts %}
    <ul>
        <li><a href="/contacts/{{ contact.id }}/">{{ contact.first_name }}</a></li>
    </ul>
    {% endfor %}
  {% endif %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM