title: Select Multiple values from a previously selected dropdown value in Django form
body: <p>I am trying to implement the steps given in this example (<a href="https://github.com/Sidon/djfkf/" rel="nofollow noreferrer">https://github.com/Sidon/djfkf/</a>) to create a Django form that allows for multiple selection of values based on a previous selection. Essentially, I have two models, one for the organism and the other for targets. Each organism can have one or more targets. I would like to select an organism, and once I've selected the organism, a drop down menu appears having all its related targets. I used opt-groups but is not giving me what I desire. Could someone kindly assist. Am new to web programming. This is just but a part of the bigger task, which is to develop a bioinformatics app. Have a look at the code for this specific purpose.</p>
  
  <pre><code>### models ####
  from django.db import models
  from django.forms import ModelForm
  from django.utils.encoding import python_2_unicode_compatible 
  from django.core.files.storage import FileSystemStorage
  import os
  from os import path
  
  @python_2_unicode_compatible  
  class reference(models.Model):
      description = models.CharField(max_length=255, blank=True)
      file = models.FileField(upload_to='documents/')
  
      def __str__(self):
          return self.description
  
  
  @python_2_unicode_compatible
  class target (models.Model):
      uploadtargetfs = os.path.join(os.getcwd(), 'targets/')
      target_name = models.CharField(max_length=255, default="") 
      reference_organism = models.ForeignKey(reference, default="")
      forward_file = models.FileField(upload_to=uploadtargetfs)
      reverse_file = models.FileField(upload_to=uploadtargetfs)
  
      def organism(self):
          return self.reference_organism.description
  
  
  
      def __str__(self):
          return self.target_name
          return self.reference_organism
  
  ##### forms ####
  import json
  from django import forms
  from django.forms import ModelForm, Textarea
  from django_select2.forms import (
      HeavySelect2MultipleWidget, HeavySelect2Widget,    ModelSelect2MultipleWidget,
  ModelSelect2TagWidget, ModelSelect2Widget, Select2MultipleWidget,
  Select2Widget
  )
  
  from .models import reference, target
  
  class ReferenceForm(forms.ModelForm):
      class Meta:
          model = reference
          fields = ('description', 'file',)
  
  class RegTargetForm(forms.ModelForm):
  
      dvarieties = {}
      list_varieties = []
      for variety in target.objects.all():
          if variety.reference_organism.description in dvarieties:
              dvarieties[variety.reference_organism.description].append(variety.target_name)
          else:
              dvarieties[variety.reference_organism.description] =     [variety.target_name]
          list_varieties.append((variety.target_name,variety.target_name))
      references = [str(reference_organism) for reference_organism in reference.objects.all()]
      reference_select = forms.ChoiceField(choices=[(reference_organism, reference_organism) for reference_organism in references])
      variety_select = forms.ChoiceField(choices=(list_varieties))
  
  
  references = json.dumps(references)
  varieties = json.dumps(dvarieties)
  
  class Meta:
      model = target
      fields = ('reference_select', 'variety_select',)
  
  
  #### views ####
  
  import os
  from os import path
  from django.conf import settings
  from django.http import HttpResponse
  from django.template import RequestContext
  from django.http import HttpResponseRedirect
  from django.shortcuts import render, redirect
  from django.shortcuts import get_object_or_404
  from django.shortcuts import render_to_response
  from django.core.urlresolvers import reverse
  from django.views.generic.edit import FormView
  from django.core.files.base import ContentFile, File
  from django.utils.datastructures import MultiValueDictKeyError
  from django.core.files.storage import FileSystemStorage
  from .models import reference, target
  from .forms import ReferenceForm, RegTargetForm
  
  def select_target(request):
  
      targets = target.objects.all()
      targets_ids = targets.values_list('id', flat=True) 
      targets_list = targets.values_list('id').values('reference_organism', 'target_name','forward_file', 'reverse_file')
      targets_queryset = targets.values('reference_organism', 'target_name','forward_file', 'reverse_file')
  
      if request.method == 'GET':
          variety_form = RegTargetForm(data=request.GET.getlist('target_choice'))
  
          if variety_form.is_valid():
              vdata = variety_form.cleaned_data.get
              variety_selected = target.objects.filter(target_name=vdata('variety_select'))
              var1 = target(reference_organism=variety_selected[0].id, target_name=vdata('target_name'))
              var1.save()
          else:
              return render(request, 'polymorph/select_target.html', {'variety_form':variety_form})
      else:
          variety_form = RegTargetForm()
      return render(request, 'polymorph/home.html', {'variety_form':variety_form})
  
  #### urls ####
  
  from django.contrib import admin
  from django.conf import settings
  from django.conf.urls import include, url
  from django.conf.urls.static import static
  from . import views
  from .views import *
  
  
  urlpatterns = [
      url(r'^$', views.index, name='index'),
      url(r'^home/$', views.home, name='home'),
      url(r'^about/$', views.about, name='about'),
      url(r'^tutorial/$', views.tutorial, name='tutorial'),
      url(r'^contact/$', views.contact, name='contact'),
      url(r'^get_reference/$', views.get_reference, name='get_reference'),
      url(r'^select_target/$', views.select_target, name='select_target'),   
  ]
  
  if settings.DEBUG:
      urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  
  
  #### select target html ####
  
  {% extends 'base.html' %}
  {% load static %}
  {% block content %}
  &lt;div class="select-style"&gt;
      &lt;form action="", method="get"&gt;
          {% csrf_token %}
          {{ variety_form.as_p }}
          &lt;p&gt;&lt;input type="submit" value="Select"&gt;&lt;/p&gt;
      &lt;/form&gt;
  &lt;/div&gt;
  {% endblock %}
  {% block js %}
      &lt;script language="javascript" type="text/javascript"&gt;
          //alert('funcionou')
          $('#id_variety_select').change(function() {populatetarget(this)});
          $('#id_reference_organism').addClass('reference_organism');
          varieties = {{ variety_form.varieties | safe }}
          references = {{ variety_form.references | safe }};
          populatereference();
          $('#id_reference_select').empty();
          $('#id_reference_select').append('&lt;option value="" disabled selected&gt;First select a reference organism&lt;/option&gt;');
  
          function populatereference() {
              $('#id_reference_select').empty();
              $('#id_reference_select').append('&lt;option value="" disabled selected&gt;Select reference organism&lt;/option&gt;');
              $.each(references, function(v) {
                  $('#id_reference_select')
                  .append($("&lt;option&gt;&lt;/option&gt;")
                  .attr("value", references[v])
                  .text(references[v]));
              });
          }
          function populatetarget(event) {
              reference = $("id_reference_select option:selected").text();
              $("id_variety_select").empty();
              $("id_variety_select").append('&lt;option value="" disabled selected&gt; Select variety&lt;/option&gt;')
              for (let [v, vvarieties] of Object.entries(varieties)) {
                  if (v == reference) {
                      //alert(v);
                      for (variety in vvarieties) {
                          $('#id_variety_select')
                              .append($("&lt;option&gt;&lt;/option&gt;")
                                  .attr("value", vvarieties[variety])
                                  .text(vvarieties[variety]));
                      }
                  }
              }
          }
      &lt;/script&gt;
  {% endblock %}
  </code></pre>
  
  <p>Kindly see the attached image displaying how I'd like it to appear</p>