Welcome to our Django tutorial on Custom Admin Templates! In this lesson, we'll guide you step-by-step on how to create custom templates for the Django admin interface. By the end of this tutorial, you'll be able to enhance the look and feel of your Django projects with personalized admin interfaces.
Django's built-in admin interface provides an easy way to manage your data. However, sometimes you might want to customize its appearance to better suit your project's style or branding. That's where custom admin templates come in handy!
Before diving into custom admin templates, ensure you have:
Let's get started by creating a new app for our custom admin template:
python manage.py startapp custom_admin_templatesInside the new app, create the following directories:
custom_admin_templates/
templates/
admin/
base.html
change_form.html
changelist.html
index.html
model_change.html
model_detail.htmlNow, let's create a basic HTML structure for each template. For simplicity, we'll reuse the base.html file for all templates.
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Your CSS and JavaScript files here -->
</head>
<body>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>Now, let's create a simple custom admin interface for a Model called MyModel. We'll modify the changelist.html and model_detail.html files to achieve this.
<!-- changelist.html -->
{% extends 'admin/base.html' %}
{% block content %}
<h1>My Custom Admin Changelist</h1>
{% block content_title %}{% endblock %}
<div id="content">
{% block content %}
<!-- List your MyModel instances here -->
{% endblock %}
</div>
{% endblock %}<!-- model_detail.html -->
{% extends 'admin/base.html' %}
{% block content %}
<h1>My Custom Admin Detail</h1>
{% block content_title %}{% endblock %}
<div id="content">
{% block content %}
<!-- Display the details of a single MyModel instance here -->
{% endblock %}
</div>
{% endblock %}Finally, let's register our custom admin template for the MyModel in the admin.py file:
# custom_admin_templates/admin.py
from django.contrib import admin
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
list_display = ('field1', 'field2')
admin.site.unregister(MyModel)
admin.site.register(MyModel, MyModelAdmin)Now, restart your Django server to see the changes in action.
Which files are required for a basic custom admin template in Django?
We hope this tutorial was helpful! Stay tuned for more lessons on Django and happy coding! ππ»