Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A-z Index Django

Tags:

python

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?

like image 396
Mark Avatar asked Sep 01 '10 10:09

Mark


People also ask

What is index in Django model?

Django Model Index was introduced in Django 1.11. what is Model. indexes: By default, indexes are created with an ascending order for each column. To define an index with a descending order for a column, add a hyphen before the field's name.

What is context preprocessor in Django?

context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. It defaults to an empty list.

How define context Django?

A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102} , when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template.


1 Answers

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.

like image 98
Mark Avatar answered Sep 22 '22 07:09

Mark