How to re-order apps and models in django admin?¶
When we register the models django automatically sorts apps by lexicographic order. But, we can do some hacks to order models and apps as we want.
Append below code in settings¶
from collections import OrderedDict
APP_ORDER = [
("app1", ["Model2", "Model1", "Model3"]),
("app2", ["Model2", "Model5", "Model3"]),
("app3", ["Model1", "Model6", "Model3"]),
]
APP_ORDER
elements should be in the format (<app_name>, [<model1>, <model2>])
Now add a template tag which will create the order¶
- Let's add the below code to the template tag
from django import template
from django.conf import settings
register = template.Library()
def pop_and_get_app(apps, key, app_label):
for index, app in enumerate(apps):
if app[key] == app_label:
obj = apps.pop(index)
return obj
return None
@register.filter
def sort_apps(apps):
new_apps = []
order = settings.APP_ORDER
for app_label in order.keys():
obj = pop_and_get_app(apps, "app_label", app_label)
new_apps.append(obj) if obj else None
apps = new_apps + apps
for app in apps:
models = app.get("models")
app_label = app.get("app_label")
new_models = []
order_models = settings.APP_ORDER.get(app_label, [])
for model in order_models:
obj = pop_and_get_app(models, "object_name", model)
new_models.append(obj) if obj else None
models = new_models + models
app["models"] = models
return apps
override the django template admin/index.html
¶
- We need to override the django admin template like below.
{% extends "admin/index.html" %}
{% block content %}
{% load i18n static admin_tags %}
<div id="content-main">
{% if app_list %}
{% for app in app_list|sort_apps %}
<div class="app-{{ app.app_label }} module">
<table>
<caption>
<a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a>
</caption>
{% if app.app_label == 'manage_templates' %}
<tr class="model-{{ model.object_name|lower }}">
<th scope="row"><a href="{% url 'admin_www_list' %}">WWW</a></th>
</tr>
{% endif %}
{% for model in app.models %}
<tr class="model-{{ model.object_name|lower }}">
{% if model.admin_url %}
<th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th>
{% else %}
<th scope="row">{{ model.name }}</th>
{% endif %}
{% if model.add_url %}
<td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td>
{% else %}
<td> </td>
{% endif %}
{% if model.admin_url %}
<td><a href="{{ model.admin_url }}" class="changelink">{% trans 'Change' %}</a></td>
{% else %}
<td> </td>
{% endif %}
</tr>
{% endfor %}
</tr>
</table>
</div>
{% endfor %}
{% else %}
<p>{% trans "You don't have permission to edit anything." %}</p>
{% endif %}
</div>
{% endblock %}