Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a custom JS file in Django admin home?

I have a heavily customized Django admin where it's very simple to load a custom JS file for each of my ModelAdmins:

class MyModelAdmin(admin.ModelAdmin):
    class Media:
        js = ('js/admin/mymodel.js',)

But how do I do this for the admin "homepage," where all my admin models are listed?

Update #1: amending my question, since the solutions below aren't that useful if I cannot efficiently include Django's jQuery. So, how do I include Django's jQuery in the JS file? If I wrap my code with (as I do in my other ModelAdmin JS files):

(function ($) {
    // my code here...
})(django.jQuery);

I get the following error:

ReferenceError: django is not defined.

Thanks.

Update #2: I was able to include Django's jQuery successfully by following this answer: https://stackoverflow.com/a/10584539/585783

like image 455
Cloud Artisans Avatar asked Nov 11 '13 15:11

Cloud Artisans


People also ask

Can I use Django admin as frontend?

Django Admin is one of the most important tools of Django. It's a full-fledged application with all the utilities a developer need. Django Admin's task is to provide an interface to the admin of the web project. Django's Docs clearly state that Django Admin is not made for frontend work.

Can we use JavaScript in Django?

While most of Django core is Python, the admin and gis contrib apps contain JavaScript code. Please follow these coding standards when writing JavaScript code for inclusion in Django.

Can I use jQuery with Django?

Inside your settings.py file make sure that django. contrib. staticfiles is under INSTALLED_APPS (it is there by default). And now you can use jQuery throughout your site!


1 Answers

You can override templates/admin/index.html and add the JavaScript in the block extrahead:

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

{% block extrahead %}
    {{ block.super }}
    # add a <script> tag here with your JavaScript
{% endblock %}
like image 80
Simeon Visser Avatar answered Oct 15 '22 13:10

Simeon Visser