models.py
class Menu(models.Model):
...
has_submenu=models.BooleanField(default=1)
page=models.ForeignKey(Page,null=True)
I want django admin shows the page attribute only if has_submenu checkbox is false (So django-admin must write some javascript for me :) )
Maybe i must extend the render_change_form
method
Any advice?
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
.
I actually had to modify this a little bit and figured I would share what I did here in case anyone else stumbles into this post. There were three main areas that I had to account for:
So, this solves all three of those problems for me. We do the following:
So this is my final code:
window.addEventListener("load", function() {
(function() {
show_page=false;
django.jQuery(document).ready(function(){
if (django.jQuery('#id_override_timeline').is(':checked')) {
django.jQuery(".form-row.field-next_milestone").show();
show_page=true;
} else {
django.jQuery(".form-row.field-next_milestone").hide();
show_page=false;
}
django.jQuery("#id_override_timeline").click(function(){
show_page=!show_page;
if (show_page) {
django.jQuery(".form-row.field-next_milestone").show();
} else {
django.jQuery(".form-row.field-next_milestone").hide();
}
})
})
})(django.jQuery);
});
I hope this helps someone else who stumbles on this post!
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With