开发者

A-z Index Django

Im looking for advice on desinging a web page with an A - Z index.

Kind of like :

http://www.bls.gov/bls/topicsaz.htm I have a long list of objects, with a title, that I want do display alphabetically, easy!

But I want to put in the A-Z with anchors, do I do this in the template,

I would have to loop through all the objects in the template, storing the currentletter as a global. Then check if each objects starts with the current letter etc etc.

It's not nice,开发者_JS百科 is there any easier way that I am missing.

Maybe I should do it in the python code?


Looking through the django template tags I found a nice way of doing it {{ifchanged}}, its worth mentioning for future use.

My list of objects is passed to my template ordered alphabetically:

Objects.get.all().order_by('title')

Then in my template i do :

# loop through all objects
{% for obj in objs %}
  #display the letter only when it changes
  {% ifchanged obj.title.0 %}<h1>{{obj.title.0}}</h1>{% endifchanged%}
  # display the object
  <h2>obj.title</h2>
{% endfor %}

Its a very handy 1 line peice of code in the template.


You may use reqroup template tag to group item... Let headline be your field to be indexed... First, in your view filter your objects and add an index parameter to each for grouping:

objectList = SomeModel.objects.all()
for x in objectList:
    x.__setattr__('index', x.headline[0])// first letter of headline

Regroup Documentation, have enough information for the rest, but simply, regrup by index and anchor item.grouper as index link...


similar to the answer of mp0int, but with adding the index on database level:

  • use .extra() to add the alphachar to the query qhere you get the objects, like:

.extra(select={'index': "SUBSTR(headline,1,1)"})

  • retrieve the data with .values()

  • use regroup in the template


There are a couple snippets that might help you:
http://djangosnippets.org/snippets/1364/
http://djangosnippets.org/snippets/1051/

The Washington Times had a nice blog post about building an alphabetical filter for the admin which might give you some helpful ideas.


You can also just use regroup directly in the template:

{% regroup object_list by name.0 as letters %} 

{% for letter in letters %}
  <div class="letter_group" id="index_{{letter.grouper}}">
    <h2>{{letter.grouper}}</h2>
    <ul>
    {% for object in letter.list %}
      <li><a href="{% url object_show object.pk %}">{{object}}</a></li> 
    {% endfor %}
    </ul>
  </div>
{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜