title: AJAX, Django and HTML Select?
body: <p>I have a form with many fields, but I have two selects, one for select the country and one for select the cities of the country that I selected.</p>
  
  <p>I want to make this: When I choose the country in the first select I want to change the cities of the second select filtered by the id of the contry that I selected.</p>
  
  <p>Here is my Models.py</p>
  
  <pre><code>class country(models.Model):
      country_name = models.CharField(max_length=264)
      def __str__(self):
          return self.country_name
  
  class country_cities(models.Model):
      city_name = models.CharField(max_length=264)
      country = models.ForeignKey(country)
      def __str__(self):
          return self.city_name
  </code></pre>
  
  <p>And Here is my HTML Form:</p>
  
  <pre><code>&lt;form method="post"&gt;
    &lt;input type="text" name="username"&gt;
    &lt;select name="country" onchange="listCities()"&gt;
      {% for country in countrylist %}
        &lt;option value="{{ country.id }}"&gt;{{ country.country_name }}&lt;/option&gt;
      {% endor %}
    &lt;/select&gt;
    &lt;select name="city" id="citylist"&gt;
      &lt;!--HERE IS WHERE I WANT TO LIST JUST THE CITIES OF THE COUNTRY THAT I SELECTED--&gt;
  
    &lt;/select&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>How do I make my view and what libraries I have to import in my views.py? Also I'm not sure if my AJAX library or my script is correct.</p>
  
  <p>AJAX:</p>
  
  <pre><code>&lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;
  &lt;/script&gt;
  </code></pre>
  
  <p>SCRIPT:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
    function listCities()
    {
      var countryid = $("[name='country']").val();
      $('#citylist').html('');
      $.ajax({
        type: "POST",
        data: "countryid="+countryid,
        url: "editprofile/",
        success: function(result)
        {
          var resultObj = JSON.parse(result);
          var dataHandler = $("#citylist");
          $.each(resultObj, function(key, val)
          {
              var newRow = $('&lt;option value="'+val.id+'"&gt;');
              newRow.html(' '+val.city_name +'');
              dataHandler.append(newRow);
          });
  
        }
      });
    }
  &lt;/script&gt;
  </code></pre>