Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...