cascading selection and fetch data from database (htmx and django)

Welcome @Siddhu2502 !

The root cause of the error message that you are getting on your form is here:

This queryset is used both to identify the elements to be shown in the select list, but also to perform the validation of the selection made when the form is submitted.

You’ll need to manage this field more “manually” than what Django provides automatically.

You’ve got a couple different options to choose from, how you handle this is up to you.

  1. You could change the queryset to .all() instead of none. Then, alter the form on the GET to empty the selection list. (You would then need to create the clean method to ensure that only a valid value was submitted.)
  2. Change the field in the __init__ method so that it .none() on the GET, and filtered by the right value on a POST.

This type of topic has been discussed a few times here previously. See the complete thread at Passing an altered queryset to ModelChoiceField and the threads linked from it as a starting point. (They may not be targeted directly at what you’re needing to do here, but the basic patterns shown are relevent.)

1 Like