将jQuery添加到Django管理页面以进行下拉选择以启用/禁用它 [英] Add jQuery to Django Admin Page for Dropdown Selection to Enable/ disable it
问题描述
我在Django中有一个包含下拉列表的模型,它们是相关的。如果我在a中选择是,则应启用与之相关的下拉列表,即b和c,如果我选择否,则应禁用它们。
I have a model in Django which contains dropdowns and they are dependent. If I select "Yes" in a, the dropdowns associated with it i.e. b and c should be enabled and if "No", they should be disabled.
希望它在管理页面上起作用。
Note that I want this to work on admin page.
models.py
class foo(models.Model):
a = models.CharField(max_length=3,choices=(('No','No'),('Yes','Yes'))
b = models.ForeignKey(SomeModel_1,,on_delete=models.CASCADE,null=True,blank=True)
c = models.ForeignKey(SomeModel_2,,on_delete=models.CASCADE,null=True,blank=True)
jQuery
$(function() {
$("#id_a").change(function() {
if ($(this).val() == "Yes") {
$("#id_b").prop("disabled", false);
$("#id_c").prop("disabled", false);
} else {
$("#id_b").prop("disabled", true);
$("#id_c").prop("disabled", true);
}
});
})(django.jQuery);
我还添加了Medi
admin.py
class fooAdmin(admin.ModelAdmin):
class Media:
js = ('https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',
'js/myScript.js',)
admin.site.register(foo,fooAdmin)
现在,下拉列表b和c都可用,无论在a中选择了什么选项。我该如何进行这项工作?如果我需要Forms.py,请解释一下该怎么做。
Now, the dropdown b and c are available regardless of choice selected in a. How can I make this work? If I need forms.py then please explain how can I do that.
谢谢。
推荐答案
我想您已经检查了脚本是否正确加载。
I suppose you have checked if your script is loading correctly.
问题是在完全加载DOM之前调用了JS函数,因此jQuery查询在调用时不会找到元素。将jQuery包装在 $(document).ready()
中:
The problem is that your JS function is called before the DOM is completely loaded, so that jQuery queries do not find the elements when called. Wrap your jQuery in $(document).ready()
:
$(document).ready(function(){
$(function() {
...
然后在页面完全加载并找到所需元素后调用它。
Then it is called after your page is completly loaded and the required elements are found.
这篇关于将jQuery添加到Django管理页面以进行下拉选择以启用/禁用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!