Django admin show field only if checked

models.py

class Menu(models.Model):

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

I want django admin to show the page attribute only if the has_submenu flag is false (so django-admin should write me javascript :))

Maybe I should extend the method render_change_form

Any tips?

+6
source share
3 answers

You can use jQuery in the Django admin area :

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

ModelAdminand InlineModelAdminhave a property mediathat returns a list of media objects that store JavaScript file paths for the form and / or form.

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

Namespaces:

, Djangos jQuery ( 3.3.1) django.jQuery.

+13

get_form ModelAdmin, :

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)

. get_form.

+2

Django.

:

:

templates/admin/change_form.html

templates/admin/<my_app>/change_form.html

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

, , . :

  • change_form.html django
  • ,
  • do a status check on has_submenu to decide whether to show or not the page attribute
+1
source

All Articles