将jQuery脚本添加到Django管理界面 [英] Adding a jQuery script to the Django admin interface
问题描述
from django.db import models
class Lab(models.Model):
acronym = models.CharField(max_length = 20)
query = models.TextField()
字段查询
与字段首字母缩略词
几乎总是相同。因此,我希望在Django的首字母缩略词
字段中输入文本后自动填写查询
字段。管理界面。这个任务必须由jQuery脚本执行。
所以如果我举个例子:你想通过Django管理界面向数据库添加一个新的实验。您单击添加按钮,并且您使用两个字段放在空的表单上。您手动填写首字母缩略词
字段,其值如 ABCD
然后查询
字段应该用相同的值完成,这意味着 ABCD
。
我继续?
要向管理员添加媒体,您可以简单地将其添加到管理类的元类媒体,例如:
admin.py
类FooAdmin(admin.ModelAdmin):
#常规东西
类媒体:
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)
注意尾随如果您只包含一个文件,则必须使用逗号,因为它必须是一个元组。您也可以以这种方式选择css。
管理员已经包含了jQuery的(较旧版本)。要快捷使用它,将其添加到myscript文件的顶部:
if(!$){
$ = django.jQuery;
}
为了解决你的问题,我会扩展管理员。您可以向任何DOM节点添加一个js事件,以在您的myscript文件中触发ajax调用,以正确的管理视图进行处理。
I'm gonna slightly simplify the situation. Let's say I've got a model called Lab.
from django.db import models
class Lab(models.Model):
acronym = models.CharField(max_length=20)
query = models.TextField()
The field query
is nearly always the same as the field acronym
. Thus, I'd like the query
field to be automatically filled in after entering text in the acronym
field in the Django admin interface. This task must be performed by a jQuery script.
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 acronym
field with a value such as ABCD
and then the query
field should antomatically be completed with the same value, that means ABCD
.
How should I proceed?
To add media to the admin you can simply add it to the meta class Media of your admin class, e.g.:
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.
The admin already has (an older version) of jquery included. To shortcut it for usage add this to the top of the 'myscript' file:
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.
这篇关于将jQuery脚本添加到Django管理界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!