Django admin: How to add a custom page?
Django admin is a powerful tool to build admin panels rapidly. With just a few lines of code, you can have a fully functional admin panel in seconds.
The problem though is customization, one of the most common customizations you'll do often is add a custom Django admin page or section.
Naturally, in doing so, you would want your custom admin section to have the same look and feel as the "ModelAdmin" or other Django Admin-generated views.
One approach is to extend the Django admin base template and register a custom route in "urls.py":
{% extends 'admin/base.html' %}
The problem with this approach is that you will not have access to any variables set by Django Admin, thus you have to get that data and pass it to the template manually. Example: the sidebar links.
Setting up a custom admin site
class CustomAdminSite(admin.AdminSite):
def get_urls(self):
custom_urls = [
path('some-custom-url/', self.admin_view(SomeCustomView.as_view(admin=self))),
]
admin_urls = super().get_urls()
return custom_urls + admin_urls
site = CustomAdminSite(name="my-fancy-url")
admin.site = site
# admin.register....your...modeladmin
The above will allow you to render your custom view at "/admin/some-custom-url".
Setting up a generic view
For our custom URL above we reference a class-based view: "SomeCustomView", here is an example implementation:
from django.shortcuts import render
from django.views.generic import ListView
class SomeCustomView(ListView):
admin = {}
def get(self, request):
ctx = self.admin.each_context(request)
return render(request, 'somecustomview.html', ctx)
Setting up the HTML template
Finally, you simply need to extend the Django admin base template and replace the content section with whatever you want to display on your page:
{% extends 'admin/base.html' %}
{% block content %}
Hello World
{% endblock %}
Conclusion
Wasn't that simple? Django admin is powerful yet cryptic sometimes, making it difficult to customize. However, once you learn the basics, Django Admin will make your life so much simpler.
Compared to other CRUD generators and admin tools, Django admin just feels clean and easy to use. Plus it will save you a ton of time.
Subscribe to my newsletter
Read articles from Kevin Naidoo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Kevin Naidoo
Kevin Naidoo
I am a South African-born tech leader with 15+ years of experience in software development including Linux servers and machine learning. My passion is web development and teaching. I often love experimenting with emerging technologies and use this blog as an outlet to share my knowledge and adventures. Learn about Python, Linux servers, SQL, Golang, SaaS, PHP, Machine Learning, and loads more.