Python 将 jQuery 脚本添加到 Django 管理界面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16014719/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:35:48  来源:igfitidea点击:

Adding a jQuery script to the Django admin interface

jquerypythondjangoadmin

提问by user2282405

I'm gonna slightly simplify the situation. Let's say I've got a model called Lab.

我要稍微简化一下情况。假设我有一个名为 Lab 的模型。

from django.db import models

class Lab(models.Model):
    acronym = models.CharField(max_length=20)
    query = models.TextField()

The field queryis nearly always the same as the field acronym. Thus, I'd like the queryfield to be automatically filled in after entering text in the acronymfield in the Django admin interface. This task must be performed by a jQuery script.

该字段query几乎总是与该字段相同acronym。因此,我希望在 Django 管理界面queryacronym字段中输入文本后自动填充该字段。此任务必须由 jQuery 脚本执行。

So if I take an example: you want to add a new lab to the database through the Django admin interface. You click the add button and you land on the empty form with the two fields. You manually fill in the acronymfield with a value such as ABCDand then the queryfield should antomatically be completed with the same value, that means ABCD.

因此,如果我举个例子:您想通过 Django 管理界面向数据库添加一个新实验室。您单击添加按钮,然后进入带有两个字段的空表单。您手动填写acronym字段的值,例如ABCD,然后该query字段应自动使用相同的值完成,这意味着ABCD.

How should I proceed?

我应该如何进行?

采纳答案by Hedde van der Heide

To add media to the admin you can simply add it to the meta class Media of your admin class, e.g.:

要将媒体添加到管理员,您只需将其添加到管理员类的元类 Media 中,例如:

admin.py

管理文件

class FooAdmin(admin.ModelAdmin):
    # regular stuff
    class Media:
        js = (
            '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', # jquery
            'js/myscript.js',       # project static folder
            'app/js/myscript.js',   # app static folder
        )

admin.site.register(Foo, FooAdmin)

Mind the trailing comma if you only have one file included, as it has to be a tuple. You can also opt in css this way.

如果您只包含一个文件,请注意尾随逗号,因为它必须是一个元组。您也可以通过这种方式选择 css。

The admin already has (an older version) of jquery included. To shortcut it for usage add this to the top of the 'myscript' file:

管理员已经包含(旧版本)的 jquery。要使用快捷方式将其添加到“myscript”文件的顶部:

if (!$) {
    $ = django.jQuery;
}

To solve your problem, I would extend the admin. You can add a js event to any DOM node to trigger an ajax call in your myscript file to the correct admin view for handling.

为了解决您的问题,我会扩展 admin。您可以将 js 事件添加到任何 DOM 节点,以触发 myscript 文件中的 ajax 调用到正确的管理视图进行处理。