Az Index Django

I need advice on creating a webpage with an index of AZ.

View like:

http://www.bls.gov/bls/topicsaz.htm I have a long list of objects with a title that I want to display in alphabetical order, simple!

But I want to add anchors to AZ, I do this in the template,

I would have to iterate over all the objects in the template, keeping the current bulletin as global. Then check if all objects start with the current letter, etc. Etc.

It’s not good if there is an easier way that I am missing.

Maybe I should do this in python code?

+4
source share
5 answers

Looking through the django template tags, I found a good way to do this {{ifchanged}} , it is worth mentioning for future use.

My list of objects is passed to my template in alphabetical order:

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

This is a very convenient 1-line piece of code in the template.

+2
source

You can use the reqroup template tag for the group element ... Let the header be indexed by your field ... First, in your opinion, filter your objects and add an index parameter for each to group:

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

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

+3
source

similar to mp0int's answer, but with the addition of index at the database level:

  • use . extra () to add alphachar to the query where you get objects, for example:

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

+2
source

There are a few snippets that can help you:
http://djangosnippets.org/snippets/1364/
http://djangosnippets.org/snippets/1051/

The Washington Times is a good blog post about creating an alphabetical filter for the admin that can give you useful ideas.

0
source

You can also just use rearrangement 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
source

All Articles