Skip to content
Advertisement

Setting a dropdowns values based on a different model selection

I currently have a model with 2 fields: Name & Number of Units

When the first field is selected e.g. Name = Name1 I would like to display the Number Of Units saved in association with that model. e.g. Name1 has 50 units then the second < select > will show the number a list from 1 – 50 because Name1 has 50 units.

When I do this with my code currently , it lists the max number of units for every model entry instead

Please see the below code:

template.html:

JavaScript

Views.py:

JavaScript

Models.py:

JavaScript

Advertisement

Answer

If you don’t want to go down the AJAX route, I’d suggest adding the maximum number of units to the first <select> and making the NumberOfUnits an Integer input field (with a minimum value validator of 1?). Form validation can further check that the number is not greater than the number available, which the user was already told about. Raise a validation error about exceeding the maximum.

JavaScript

and in your form override the clean method to check

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement