简体   繁体   中英

Django 1.6: Two dropdown menus in one single form not working

I've two dropdown menus in one single template. They both are using the same form. But for some reason only one of the form works and gives me MultiValueDictKeyError in the views. It gives me error on the line request.session["genderselect"] = request.POST['genderselect']

So I've commented out the lines to see what happens and the code works and shows the first dropdown (name = selection). But the second dropdown of (name = genderselect) doesn't work, although they both are part of the same form.

views.py

def doclistings(request):
    d = getVariables(request)
    if request.method == "POST":
        form = DropdownSelectionForm(request.POST)

        if form.is_valid():
            print form.errors
            selection = form.cleaned_data['selection']
            # genderselect = form.cleaned_data['genderselect']
            # request.session["genderselect"] = request.POST['genderselect']
            request.session["selection"] = request.POST['selection']

            return HttpResponseRedirect('/doclistings')
    else:
        form = DropdownSelectionForm()

    # d['genderselect'] = genderselect
    s_name = request.session.get('selection')  
    d['userselection'] = s_name  
    spec = Specialization.objects.get(name=s_name) 
    doctors = Doctor.objects.filter(specialization = spec).order_by('-likes')  
    d['doctors'] = doctors

    d.update({'form': form})
    return render_to_response('meddy1/doclistings.html',d)

forms.py

class DropdownSelectionForm(forms.Form):
    selection = forms.ChoiceField(choices=MY_CHOICES, widget = forms.Select, required = False)
    genderselect = forms.ChoiceField(choices=GENDER_CHOICES, widget= forms.Select, required = False)

here is the template where I've the two dropdown

    <select class="form-control" id="selection" name="selection">
      <option><b>Find a Doctor...</b></option>
      {% for value, text in form.selection.field.choices %}
        <option value="{{ value }}">{{ text }}</option>
      {% endfor %}
    </select>

      <select class="form-control" id="genderdropdown" name="genderdropdown">
      <option><b>Select a Gender</b></option>
      {% for value, text in form.genderselect.field.choices %}
        <option value="{{ value }}">{{ text }}</option>
      {% endfor %}
    </select>

    <span class="input-group-btn">
      <button class="btn btn-primary" type="submit"  name="submit" id="ss-submit">Search</button>
    </span>
  </div>
  {% csrf_token %}

</form>

You should change the name="genderdropdown" attribute to match the form field name.

In other words, replace name="genderdropdown" with name="genderselect" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM