Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin: Need to conditionally display fields

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

In particular I'm thinking about the add_form and change_form. Whenever a certain choice is selected I'd like to hide or disable some fields.

I'm thinking that this might require a javascript solution, but am wondering if there is a better (i.e. builtin) way to do this.

like image 744
IntrepidDude Avatar asked Jan 13 '11 23:01

IntrepidDude


People also ask

How can we make field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

How do you make a field non editable in Django admin?

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm.

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

What does admin do in Django?

The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.


1 Answers

Bernhard is right. You might be able to hack the admin view and template to conditionally show/not show widgets for a field, but if you want to do it dynamically based on user behaviors in the admin, you'll be using javascript.

It's not so terrible, though. At least the Django admin templates have model- and instance-specific ids to give you granular control over your show/hide behavior.

like image 119
Jeremy Bowers Avatar answered Sep 28 '22 02:09

Jeremy Bowers