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

邮差的信 提交于 2020-02-05 04:34:27

问题


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

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. How can I make this work? If I need forms.py then please explain how can I do that.

Thank you.


回答1:


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. 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.



来源:https://stackoverflow.com/questions/59588858/add-jquery-to-django-admin-page-for-dropdown-selection-to-enable-disable-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!