models.py
class Menu(models.Model):
...
has_submenu=models.BooleanField(default=1)
page=models.ForeignKey(Page,null=True)
I wa
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:
You can use jQuery within the Django admin:
class MenuAdmin(admin.ModelAdmin):
# ...
class Media:
js = ('/static/admin/js/hide_attribute.js',)
ModelAdmin
andInlineModelAdmin
have amedia
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
.
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.