简体   繁体   English

将 jQuery 添加到 Django 管理页面以进行下拉选择以启用/禁用它

[英]Add jQuery to Django Admin Page for Dropdown Selection to Enable/ disable it

I have a model in Django which contains dropdowns and they are dependent.我在 Django 中有一个模型,其中包含下拉列表并且它们是相关的。 If I select "Yes" in a, the dropdowns associated with it ie b and c should be enabled and if "No", they should be disabled.如果我在 a 中选择“是”,则应启用与其关联的下拉列表,即 b 和 c,如果选择“否”,则应禁用它们。

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 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);

And I have also added Media class而且我还添加了媒体类

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)

Now, the dropdown b and c are available regardless of choice selected in a.现在,无论 a 中的选择如何,下拉 b 和 c 都可用。 How can I make this work?我怎样才能使这项工作? If I need forms.py then please explain how can I do that.如果我需要 forms.py 那么请解释我该怎么做。

Thank you.谢谢你。

I suppose you have checked if your script is loading correctly.我想您已经检查过您的脚本是否正确加载。

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.问题是您的 JS 函数在 DOM 完全加载之前被调用,因此 jQuery 查询在调用时找不到元素。 Wrap your jQuery in $(document).ready() :将您的 jQuery 包裹在$(document).ready()

$(document).ready(function(){
    $(function() {
    ...

Then it is called after your page is completly loaded and the required elements are found.然后在您的页面完全加载并找到所需元素后调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM