django admin show field only if checkbox is false

前端 未结 3 1032
独厮守ぢ
独厮守ぢ 2020-12-29 13:46

models.py

class Menu(models.Model):

    ...
    has_submenu=models.BooleanField(default=1)
    page=models.ForeignKey(Page,null=True)

I wa

相关标签:
3条回答
  • 2020-12-29 14:38

    You could extend Django admin template.

    Just follow this structure:

    Across an entire project:

    templates/admin/change_form.html
    

    Across an application

    templates/admin/<my_app>/change_form.html
    

    Across a Model

    templates/admin/<my_app>/<my_model>/change_form.html
    

    In your case, looks like you only need to extend the Menu model. I would do the following:

    1. grab the change_form.html teamplate from django folder
    2. inside the object loop, look for the page field
    3. do the condition check on has_submenu to decide whether to show or not the page attribute
    0 讨论(0)
  • 2020-12-29 14:39

    You can use jQuery within the Django admin:

    class MenuAdmin(admin.ModelAdmin):
        # ...
        class Media:
            js = ('/static/admin/js/hide_attribute.js',)
    

    ModelAdmin and InlineModelAdmin have a media property that returns a list of Media objects which store paths to the JavaScript files for the forms and/or formsets.

    Contents of hide_attribute.js:

    hide_page=false;
    django.jQuery(document).ready(function(){
        if (django.jQuery('#id_has_submenu').is(':checked')) {
            django.jQuery(".page").hide();
            hide_page=true;
        } else {
            django.jQuery(".page").show();
            hide_page=false;
        }
        django.jQuery("#id_has_submenu").click(function(){
            hide_page=!hide_page;
            if (hide_page) {
                django.jQuery(".page").hide();
            } else {
                django.jQuery(".page").show();
            }
        })
    })
    

    Namespacing:

    To avoid conflicts with user-supplied scripts or libraries, Django’s jQuery (version 3.3.1) is namespaced as django.jQuery.

    0 讨论(0)
  • 2020-12-29 14:46

    How about overriding get_form method on a ModelAdmin, like this:

    class MenuModelAdmin(admin.ModelAdmin):
        def get_form(self, request, obj=None, **kwargs):
            self.exclude = []
            if obj and obj.has_submenu:
                self.exclude.append('page')
            return super(MenuModelAdmin, self).get_form(request, obj, **kwargs)
    

    Also, please, see get_form docs.

    0 讨论(0)
提交回复
热议问题