[Django]-Select a valid choice. That choice is not one of the available choices

6👍

This is because you initialize your queryset empty (which is fine), but never update it within the form object itself. So the server side validation is failing.

Try updating your queryset in the __init__ method of your FeesCreationForm:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    # Init empty did queryset
    self.fields['did'].queryset = DepartmentData.objects.none()

    # Get did queryset for the selected fid
    if 'fid' in self.data:
        try:
            fid = int(self.data.get('fid'))
            self.fields['did'].queryset = DepartmentData.objects.filter(
                fid=fid).order_by()
        except (ValueError, TypeError):
            # invalid input from the client; ignore and use empty queryset
            pass
👤Sergio

1👍

(paraphrasing)

I have a dropdown that’s depending on a previously selected value from another dropdown

I had a similar problem in the past. Does this answer your question? The basic idea is, you can send all the correct information to the client you want, but at the end of the day the server should be validating that the correct set of options were used. Django is getting mad because it thinks the choice sent to the server for the 2nd dropdown is invalid. After receiving the POST, you need to dynamically get the 2nd dropdown’s choices BASED ON whatever was sent as dropdown #1’s choice AND THEN try and validate the form.

👤Rosey

Leave a comment