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.
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.
Here is my Models.py
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
And Here is my HTML Form:
<form method="post">
<input type="text" name="username">
<select name="country" onchange="listCities()">
{% for country in countrylist %}
<option value="{{ country.id }}">{{ country.country_name }}</option>
{% endor %}
</select>
<select name="city" id="citylist">
<!--HERE IS WHERE I WANT TO LIST JUST THE CITIES OF THE COUNTRY THAT I SELECTED-->
</select>
</form>
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.
AJAX:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
SCRIPT:
<script type="text/javascript">
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 = $('<option value="'+val.id+'">');
newRow.html(' '+val.city_name +'');
dataHandler.append(newRow);
});
}
});
}
</script>