DEV Community

Cover image for Django admin: How to add a custom page?
Kevin Naidoo
Kevin Naidoo

Posted on • Originally published at kevincoder.co.za

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' %}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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 %}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)