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

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


Let's say here what you've got for models:

# Model B
class ModelB(models.Model):
    pass

# Model A
class ModelA(models.Model):
    b_link = models.ForeignKey(ModelB)

I assume that you don't want to use javascript to manipulate the form but parsing it from server. In that case, what you can do is just create a preview Model B, and create the ModelForm from this model.
For example:

class ModelB(models.Model):
    ...
    # add a method to preview B - This will not save model
    def preview_b(model_a):
        # update values of b according to model_a
        b.derived_value = model_a.value

# file: forms.py
class ModelBForm(ModelForm):
    class Meta:
        model = ModelB

# file: views.py
b_model = Model.objects.all().first()
b_model.preview_b(a_model)
form = ModelBForm(instance=b_model)

This, of course, requires you to post back to server whenever choosing a new ModelA but I think that was what you wanted.

Tags:

Django