Learn Wagtail Course

Adding Custom CSS and JavaScript to Your Admin Area

How to tell Wagtail to add custom files to your /admin/

Wagtail comes with a feature called Hooks. These hooks are functions that get called at a certain time, and you can write hooks to execute functions at different points in time when your page(s) load.

Here we're using two hooks:

  1. insert_global_admin_css, and
  2. insert_global_admin_js

To see a full list of hooks, check out the Wagtail Documentation on Hooks.

Let's take a look at how to add these hooks. It's actually quite simple.

The code

"""File: core/wagtail_hooks.py."""

from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import format_html

from wagtail.core import hooks

@hooks.register("insert_global_admin_css", order=100)
def global_admin_css():
    """Add /static/css/custom.css to the admin."""
    return format_html(
        '<link rel="stylesheet" href="{}">',
        static("css/custom.css")
    )


@hooks.register("insert_global_admin_js", order=100)
def global_admin_js():
    """Add /static/css/custom.js to the admin."""
    return format_html(
        '<script src="{}"></script>',
        static("/js/custom.js")
    )

Basically, we import static, format_html and hooks, then create 2 new functions, and register the functions as hooks using the @hooks.register decorator.

Now if you load up the site in your browser (ie. http://localhost:8000/) and:

  1. Right click on the page,
  2. Select "View Page Source"

You will be able to see custom.css and custom.js in there. But at this point in time those files don't exist, so if you tried to open custom.css or custom.js in your browser, you'll get a 404.

The static files

The last thing you need to do is make sure these files exist. In the video I created files that were located at:

  1. /static/css/custom.css, and
  2. /static/js/custom.js

If you create these files in your project and restart Django, you shouldn't be prompted with a 404 if you view the files (although they will be empty by default).

It's at this point you can customize your CSS and JavaScript anyway you want. Personally I like using these two hooks for branding the website for customers and clients. The extra 20 minutes to change a few colours goes a long way in the eyes of your client.

The Git Commit

Want to see the entire Git commit? No problem! Here's the link to see everything that was changed in this tutorial: https://github.com/CodingForEverybody/learn-wagtail/commit/bd533b96e6f6297e5c5ebf011f6d544f56f6ab88

Was this helpful to you?

Sharing is caring. Help the community by sharing this article.