jwerardi jwerardi - 1 year ago 79
Python Question

How would you create two select menus where select menu B's contents are dependent on select menu A's selection?

How do you create two select menus with one dict where select menu B has values that correspond and are dependent to the keys present in select menu A?

In my Django views.py, I've created a dictionary that has a lists of Projects as keys, and corresponding Tasks as values within the dictionary. It looks like the following

Project A: Task 1

Project A: Task 2

Project A: Task 3

Project B: Task 1

Project B: Task 2

Project C: Task 1


I've been able to successfully pass this information into my Django template, but I can't wrap my head around how I can do what I need to do with the information.

I need to be able to take the information in the keys, ie the Projects, and create a drop down menu (A) which, when a key is selected, will display all of the corresponding tasks for the key in a second drop down menu (B)

I'm up to any kind of solution. I'm thinking about using jquery and hacking something together, but I'm really at a loss as to how to begin. Does anyone have experience with something like this?

Answer Source

You can use django-autocomplete-light to do this. This basically provides autocompletion using a client library such as select2. But it also provides a way to filter results based on another field.

You should likely also make a server verification in the form clean:

class MyForm(forms.Form):

    project = forms.ModelChoiceField(queryset=Project.objects.all())
    task = forms.Model.ChoicField(queryset=Task.objects.all())

    def clean(self):
        project = self.cleaned_data['project']
        task = self.cleaned_data['task']
        if task.project_id != project.pk:
            raise forms.ValidationError(
                "The selected task does not belong to the selected project.")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download