Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin update of form fields based on foreign key model selection

Tags:

django

In django admin I have Model A with a foreign key association to Model B. Model B's values change based on the value of Model A.

When a Model B object is selected for association with a Model A object, I would like to immediately display updated values for Model B based on the current value of Model A.

I know that I can override the on_save method in the form to update the values when the user saves the form to the database. However, I would like the admin view to display the values before the user hits save.

What do I need to hook into to make this update happen?

Thank You

like image 822
JHRS Avatar asked Dec 01 '17 03:12

JHRS


1 Answers

If you want to dinamically filter Model B values in the changeview during user interaction (that is: before submission), you need javascript:

1) after page rendering, attach a "change handler" to Model A input field

2) in that handler, call via Ajax a view to retrieve the list of values available for Model B according to the currently selected value of Model A

3) upon receiving the list, update the Model B input field accordingly

4) also, after the initial page rendering you should explicitly invoke the handler in order to have Model B input field correctly initialized

This should work for both "add" and "change" view.

I do believe that a very detailed tutorial on how to implement this procedure can be found here:

https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

The example refers to a front-end view, but can be easily adapted to the admin changeview

like image 177
Mario Orlandi Avatar answered Sep 23 '22 02:09

Mario Orlandi