Custom Django Admin Add Template

Summary

How to: customize Django Admin model templates

Status
Published
Created On
Nov 12, 2023 4:45 AM
Updated On
Nov 14, 2023 7:29 AM

Custom Django Admin Add Template

{{ page_properties }}

Overview

In this post we’ll update the add_form template for a model, the same logic can be applied to other admin model templates.

See list of all templates which can be overridden: https://docs.djangoproject.com/en/4.2/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model

Create Template File

In your project directory, create a file at this path: templates/admin/<app_name>/<model>/add_form.html

For example, if you have an app named books and a model named author, the path would be: templates/admin/books/author/add_form.html

Extend Template

Extend the base admin change_form template, instead of writing an entirely new template.

{% extends "admin/change_form.html" %}

{% load i18n %}

If you’re using unfold, update load tag to be {% load i18n unflold %}

Next modify specific blocks in the template, for example:

{% extends "admin/change_form.html" %}

{% load i18n unfold %}

{% block field_sets %}
	<p>Hello World!</p>
	{{ block.super }}
{% endblock %}

Update Admin Model Class

Update your model’s admin class to load the new add_form template.

@admin.register(MyModel)
class MyModelAdmin(ModelAdmin):
		...
    add_form_template = "admin/<project>/<model>/add_form.html"
		...

When you go to add a new model you should see “Hello World!” above the fields.

Related Posts

Knowledge Base: Django Generic Fields

Guidelines and Answers to all things Django Generic Fields

Nov 14, 2023 7:33 AM
Custom Django Unfold Admin Dashboard

Setup a custom admin dashboard in an existing repo, exactly like the one shown on Unfold Formula Demo project.

Nov 14, 2023 7:29 AM
🔒
Django x React Native Authentication

Implementing Google and Microsoft Azure Active Directory OAuth in Django Rest Framework and React Native Expo

Nov 14, 2023 7:28 AM

🦄⚡