Xar
Xar

Reputation: 7910

Django Form: "Select a valid choice. That choice is not one of the available choices."

I'm working with Python2 and Django 1.9.

Basically I have a form that contains two dropdowns. The second dropdown depends on the value of the first one.

For exampe, if dropdown #1 has the option "Category" selected, then dropdown #2 should display options "CategoryA, CategoryB and CategoryC". In the same way, if dropdown#1 has the option "Department" selected, Dropdown#2 should show "Department1, Department2, Department3".

Notice that both "Departments" and "Categories" are classes with their corresponding database tables.

So here comes my question. How to define that form? More especifcally, how do I indicate that the second form will sometimes display objects from the class Category and sometimes objects of the class Department?

This is what I have so far:

class MyClassForm(forms.Form):]
    name = forms.CharField(max_length=255)
    dropdown1 = forms.ModelChoiceField(
        queryset=TypeOfCriteria.objects.all().order_by('name'))
    dropdown2 = forms.ModelChoiceField(
        queryset=Department.objects.none())

Notice how I've defined dropdodown2:

    dropdown2 = forms.ModelChoiceField(
        queryset=Department.objects.none())

How should I define the value of the parameter queryset for dropdown2? Since I have to specify the class that is going to be queried to obtain the list of all of its instances, how should I do it?

Right now, I'm loading the content of dropdown2 with JQuery. But when I hit the "send" button to send the post data I'm always getting the error: "Select a valid choice. That choice is not one of the available choices."

Upvotes: 2

Views: 2724

Answers (2)

German Alzate
German Alzate

Reputation: 821

In the init method

    def __init__(self,  *arts,  **kwargs):
      super(MyClassForm, self).__init__(*args, **kwargs) 
      self.fields['dropdown2'].queryset = Department.objects.none()
      if self.is_bound:
         self.fields['dropdown2'].queryset = Department.objects.filter(# any value in self.data) 

Upvotes: 2

raphv
raphv

Reputation: 1183

One option would be to update the queryset dynamically in the __init__ method of the form. Keep the rest of your form class as is, then add this code:

def __init__(self, *args, **kwargs):
    super(MyClassForm, self).__init__(*args, **kwargs)
    if 'dropdown1' in self.data:
        self.fields['dropdown2'].queryset = Department.objects.filter(typeofcriteria=self.data['dropdown1'])

Upvotes: 4

Related Questions