tags:

views:

67

answers:

4
+2  Q: 

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, is there any easier way that I am missing.

Maybe I should do it in the python code?

+3  A: 

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...

FallenAngel
+1  A: 

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)"})

Andre Bossard
+1  A: 

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.

Mark
A: 

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.

Mark Lavin