Overriding admin css in django
I want to change certain css in admin django like base.css. Is it better to change directly in the django library? How can I override it in the best way?
It depends a lot of what you want to do. Though first of all: do not overwrite it in the Django admin directly. You got two options I think are reasonable:
- If you want to change the appearance of the admin in general you should override admin templates. This is covered in details here: Overriding admin templates. Sometimes you can just extend the original admin file and then overwrite a block like
{% block extrastyle %}{% endblock %}
indjango/contrib/admin/templates/admin/base.html
as an example. - If your style is model specific you can add additional styles via the
Media
meta class in youradmin.py
. See an example here:
class MyModelAdmin(admin.ModelAdmin): class Media: js = ('js/admin/my_own_admin.js',) css = { 'all': ('css/admin/my_own_admin.css',) }
- In
settings.py
, make sure your app is listed before admin in theINSTALLED_APPS
. - Create
(your-app)/templates/admin/base_site.html
and put the<style>
block into the{% block extrahead %}
Example:
{% extends "admin/base_site.html" %}
{% block extrahead %}
<style>
.field-__str__ {
font-family: Consolas, monospace;
}
</style>
{% endblock %}
This solution will work for the admin site, I think it's the cleanest way because it overrides base_site.html
which doesn't change when upgrading django.
Create in your templates directory a folder called admin
in it create a file named base_site.html
.
Create in your static directory under css
a file called admin-extra.css
.
Write in it all the custom css you want for your forms like: body{background: #000;}
.
Paste this in the base_site.html
:
{% extends "admin/base.html" %}
{% load static from staticfiles %} # This might be just {% load static %} in your ENV
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "css/admin-extra.css" %}" />{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
As mentioned in the comments: make sure your app is before the admin app in INSTALLED_APPS, otherwise your template doesn't override django's
That's It! you're done
I just extended admin/base.html to include a reference to my own css file - at the end. The beauty of css is that you don't have to touch existing definitions, just re-define.