How to collapse only one field in Django admin?

The django admin allows you to specify fields . You correctly structure a tuple that groups different fields together. You can also specify classes for specific field groups. One of these classes is collapse, which will hide the field under the drop area. This is useful for hiding rarely used or advanced fields in order to support the user interface.

However, I have a situation where I want to hide only one single field in many different applications. It will be a lot to create a complete fieldset specification in each admin.py file to put one field in a folded area. This also creates a difficult maintenance situation, because I will have to edit the field fields every time I edit the associated model.

I can easily exclude the entire field using the exclude parameter. I want something like this to crash. Is it possible?

+4
source share
3 answers

Django has no built-in way to do this that I know of, but I can come up with a couple of ways that you could do something once, instead of manually modifying many fields.

One approach is to use javascript to overwrite page layout. Perhaps javascript may have a list of field names and whenever it finds one of them, it hides the field and its label and adds a button to the page to switch these invisible fields.

Another approach would only include python. Usually you simply specify the fieldsets attribute in admin as a tuple. But you can specify it as an imported function that takes a regular tuple as an argument. In your settings file, you can specify a list of field names that you want to hide. Then you need to write a function that returns the modified tuple, moving any fields that match one of your field names to a new set of fields along with the collapse class.

For example, in your admin class, you can do something like this (you need to write and import hide_fields).

fieldsets = hide_fields( (None, {'fields':('title', 'content')} ) ) 

This can be interpreted as the following: it is assumed that the contents are in the settings file as something you want to hide:

 fieldsets = ( (None, {'fields':('title',)} ), ('Extra', { 'fields': ('content',), 'classes':('collapse',), } ), ) 
+2
source

I am doing something like this where I have one or more fields that are only required based on the value of the other. Usually this is a checkbox or choice where true / false or one specific value means that we should show this other set of fields. I added something like this:

 $(document).ready(function(){ function show_hide() { var is_checked = $('#id_first_field').attr('checked'); $('.second_field')[is_checked ? 'show' : 'hide'](); } show_hide(); $('#id_first_field').change(show_hide); }); 
0
source

If you want, you can use fieldset in your admin.py, and the field you want to collapse uses the class as a failure and remains as foobar.

Refer to django docs

-3
source

Source: https://habr.com/ru/post/1303725/


All Articles