0
votes

I'm seeking guidance to get me going in the right direction. My professor is at a loss. I'm having issues with the POST in my form for the select2 multiple fields. I have a Yes/No flag, that determines which select 2 select option to show.

The javascript below works great for the show/hide.

   $(document).ready(function () {

      $('#option').change(function () {
        $this = $(this)
        $('.select_box').each(function () {
          $select = $('select', this);
          if ($select.data('id') == $this.val()) {
            $(this).show();
            $select.show().select2();
          } else {
            $(this).hide();
            $('select', this).hide();
          }
        });
      });
    });

My form has a Yes/No/NA option, which dictates what select 2 box to show using the javascript above.

<select name ="option" class="form-control " id="option">
        <option value="1"> Yes</option>
        <option value="0"> No</option>
        <option value="2"> N/A</option>
</select>

My form POST is handled with the general POST option as shown below:

<form action = "{% url 'final' %}" form method = "POST">

Inside my form I have the .select_box div class. The select 2 option gives the correct fields and populates the multi-select correctly.

<div id = "div_yesselect" class="select_box">
    <script src= "{% static '/accounts/option_select2.js' %}" type="text/javascript"></script>
     <select data-placeholder="Please select your course(s)?" data-id="1" class="js-example-basic-multiple" multiple="multiple" id = "id_courseselect" value = "{{course.id}}" style="width: 1110px" >
       {% for course in courses%}
       <option value="{{course.name}}" name = "courseid" >{{course.name}}</option>
       {% endfor %}
     </select>

The POST goes through when the user hits the Submit Button. I can verify all the fields in my form except for the select2 option when a user selects multiple options, or a single option.

<button class="btn btn-primary " type="submit">Submit</button>

In my final view when trying to request the POST on the select2 name it returns an empty set, but everything else in the form returns the correct value. Why doesn't the select2 option post correctly?

courselist = request.POST.getlist('courseid')
1

1 Answers

1
votes

Form POST in Django depends on name attributes. When you request courseid, it's going to look for an element with name attribute equal to courseid, meaning:

courselist = request.POST.getlist('courseid')

needs a matching element, for example

<select name="courseid" multiple>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

You need to add name attribute to your select element and it should work.