Hide shortcut in django admin fieldset readonly field

I have a very annoying problem that I cannot hide the label in admin if the field is read-only:

class Observable(Model): constraints=ManyToManyField('Constraint') class ObservableAdmin(MPTTModelAdmin): form=ObservableAdminForm fieldsets =[('other fields',{}), ('All Constraints...:', {'fields':('constraints',)}),] readonly_fields = ['constraints'] # I want to hide the "Constraints: " label class ObservableAdminForm(ModelForm): class Meta: model=Observable fields=('parent', 'name', 'alias', 'comments', 'constraints') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # CAN'T DO self.fields['constraints'].label='' 

The problem is that the readonly field defined in admin does not appear at all in the modelform fields.

The django admin correctly displays the constraints as a comma-separated block of text, but it shows the โ€œConstraintsโ€ label, which is redundant with โ€œAll constraints ...โ€ in the set of fields. Can anyone suggest a workaround?

thanks Danny

+4
source share
2 answers

I realized a really ugly workaround that does what I want ...

I hacked fieldset.html to include the following:

 {% if field.label_tag != "<label>Constraints:</label>" %} {{ field.label_tag }} {% endif %} 

So that the label label fieldset does not appear for the Constraints field, but is not affected otherwise.

Do not try this at home ...

+3
source

An admin form is created dynamically from the metaclass when add_view or change_view is called (see the adminForm variable in django/contrib/admin/options.py ).

So the easiest workaround is to put None in the fieldset label:

 class ObservableAdmin(MPTTModelAdmin): form=ObservableAdminForm fieldsets =[('other fields',{}), (None, {'fields':('constraints',)}),] readonly_fields = ['constraints'] # I want to hide the "Constraints: " label 

Alternatively, you can set an empty label using the verbose_name attribute in the model field declaration:

 class Observable(Model): constraints=ManyToManyField('Constraint', verbose_name='') 

but you cannot remove the label suffix (':') because it is fixed in the code ( django/contrib/admin/helpers.py ).

I prefer the first solution whenever possible (the appropriate label is needed for a set of fields if you want to hide it with collapse ).

0
source

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


All Articles