javascript 如何在 Django 管理主页中加载自定义 JS 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19910450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load a custom JS file in Django admin home?
提问by Cloud Artisans
I have a heavily customized Django admin where it's very simple to load a custom JS file for each of my ModelAdmins:
我有一个高度定制的 Django 管理员,为我的每个 ModelAdmin 加载一个定制的 JS 文件非常简单:
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):
更新 #1:修改我的问题,因为如果我不能有效地包含 Django 的 jQuery,那么下面的解决方案就没那么有用了。那么,如何在 JS 文件中包含 Django 的 jQuery?如果我用以下方式包装代码(就像我在其他 ModelAdmin JS 文件中所做的那样):
(function ($) {
// my code here...
})(django.jQuery);
I get the following error:
我收到以下错误:
ReferenceError: django is not defined.
参考错误:django 未定义。
Thanks.
谢谢。
Update #2: I was able to include Django's jQuery successfully by following this answer: https://stackoverflow.com/a/10584539/585783
更新 #2:通过遵循以下答案,我能够成功包含 Django 的 jQuery:https: //stackoverflow.com/a/10584539/585783
回答by Simeon Visser
You can override templates/admin/index.html
and add the JavaScript in the block extrahead
:
您可以templates/admin/index.html
在块中覆盖和添加 JavaScript extrahead
:
{% extends "admin/index.html" %}
{% block extrahead %}
{{ block.super }}
# add a <script> tag here with your JavaScript
{% endblock %}