"""

Author: Harmanas S. C.

Description:

    Was inspired by: http://djangosnippets.org/snippets/1939/
    I rewrote it from scratch because it wasn't working on my
    install.

Installation Instructions:
    1) Specify app ordering in settings.py
    2) Place the custom templatetag in one of your installed
    apps templatetag folders.
    3) Add the template code to your 'admin/index.html'
    template.

"""

"""
1) In settings.py
"""
...
...
ADMIN_REORDER = (
        ("Auth", ("Users", "Groups")), 
        ("Dashboard", ("Dashboards", "Querys", "Query templates", "Charts")),
        ("Sites", ("Sites"))
)
...
...


"""
2) In /templatetags/custom_tags.py
"""

from django.template.base import Node, NodeList, Template, Context, Variable
from django.template.base import get_library, Library, InvalidTemplateLibrary
from django import template
from django.conf import settings
from string import strip, replace
from re import sub

class AppOrderNode(Node):
    """
        Reorders the app_list and child model lists on the admin index page.
    """
    def render(self, context):
        if 'app_list' in context:
            app_list = list(context['app_list'])
            ordered = []
            # look at each app in the user order
            for app in settings.ADMIN_REORDER:
                app_name, app_models = app[0], app[1]
                # look at each app in the orig order
                for app_def in app_list:
                    if app_def['name'] == app_name:
                        model_list = list(app_def['models'])
                        mord = []
                        # look at models in user order
                        for model_name in app_models:
                            # look at models in orig order
                            for model_def in model_list:
                               if model_def['name'] == model_name:
                                   mord.append(model_def)
                                   model_list.remove(model_def)
                                   break
                        mord[len(mord):] = model_list
                        ordered.append({'app_url': app_def['app_url'],
                            'models': mord, 'name': app_def['name']})
                        app_list.remove(app_def)
                        break
            ordered[len(ordered):] = app_list
            context['app_list'] = ordered
        return ''

def app_order(parser, token):
    return AppOrderNode()
var = register.tag(app_order)


"""
3) In 'admin/index.html' template.
"""

...
...
{% load custom_tags %}
{% if app_list %}
    {% app_order %}
    {% for app in app_list %}
        <div class="module table_module">
...
...