如何在Django admin中加载自定义的JS文件? [英] How to load a custom JS file in Django admin home?

查看:1970
本文介绍了如何在Django admin中加载自定义的JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大量定制的Django管理员,它为我的每个ModelAdmins加载自定义的JS文件非常简单:

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

但是,如何管理所有管理员模型的管理员首页呢?



更新#1 :修改我的问题,因为如果我无法有效地包含Django的jQuery,下面的解决方案不是很有用。那么,如何在JS文件中包含Django的jQuery?如果我包装我的代码(如我在其他ModelAdmin JS文件中):

 (function($){// ...})(django.jQuery); 

我收到以下错误:


ReferenceError:django未定义。


谢谢。



更新#2 :我能够通过以下回答成功地包含Django的jQuery: https: //stackoverflow.com/a/10584539/585783

解决方案

您可以覆盖模板/admin/index.html ,并在块 extrahead 中添加JavaScript:

  {%extendsadmin / index.html%} 

{%block extrahead%}
#添加< script>在这里用你的JavaScript标记
{%endblock%}


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 ($) { //... })(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

解决方案

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

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

{% block extrahead %}
    # add a <script> tag here with your JavaScript
{% endblock %}

这篇关于如何在Django admin中加载自定义的JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆