Django Admin: it is necessary to conditionally display fields

What is the best way to conditionally display a field in the admin panel depending on the values ​​of other fields?

In particular, I am thinking of add_form and change_form. Whenever a specific selection is selected, I would like to hide or disable some fields.

I think this might require a javascript solution, but I'm wondering if there is a better way (e.g. built-in) for this.

+8
django django-admin
source share
3 answers
Bernhard is right. You may be able to hack into the administrator’s view and template to conditionally show / not display widgets for the field, but if you want to do this dynamically based on user behavior in the admin, you will use javascript.

It's not so scary. At the very least, Django admin templates have model and instance specific identifiers to give you detailed control over your show / hide action.

+1
source share

I think you should create your own ModelForm and indicate that the administrator is using this ( https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form ).

Use the _init __ () method of the form to selectively display fields.

I will give it a try and update this answer if it works.

(Actually, re-reading the question, it depends. If the “values ​​of other fields” are set before the page loads, this idea should work. If you want an instant answer, click on one field and the other will appear / disappear, but you need JavaScript).

0
source share

My answer may sound esoteric - but I suspect that the design direction you can take may benefit from some revision. When an interface requires a lot of TLC to resort to AJAX in order to make an excellent UX, I tend to not use the Admin interface for this.

My personal idea of ​​the Django admin interface is that it is a great freebie that gives me an instant CRUD look at a basic level. I would refrain from supporting copies for those who need a more convenient interface (even if some of these users handle administrator functions). You will get technical debt in an attempt to perform these types of Ajax UI / UX and complex form validation using the admin interface.

0
source share

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


All Articles