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>
I used getJSON instead of POST for something similar. This assumes that you take out onchange from HTML and use change within jQuery instead, with a select box ID of #countrylist. It uses the value from the select box as the lookup id for country.
You'll need a view for the ajax call, too. The url variable in the AJAX portion will hook to that. Your views.py and script.js could have something like this:
#views.py
#...other imports...
from django.core import seralizers
def select_country(request):
if request.method == 'GET' and request.is_ajax():
selected_country = request.GET.get('id')
json_city = serializers.serialize("json", country_cities.objects.filter(country_id = selected_country))
return HttpResponse(json_city, content_type='application/json')
else:
return HttpResponse("no-go")
#YourScript.js
$(function(){
//...your AJAX configurations would go up here, like CSRF stuff...
$(document).on('change', "#countrylist", function(e) {
e.preventDefault();
console.log($(this).val());
var url = http://127.0.0.1:8000/yourURLtoView
$.getJSON(url, {id: $(this).val()}, function(j) {
var options = '<option value="">---??---</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + parseInt(j[i].pk) + '">' + j[i].fields['city_name'] + '</option>';
}
console.log(options); //This should show the new listing of filtered options.
$("#citylist").html(options);
$("#citylist option:first").attr('selected', 'selected');
});
$("#countrylist").attr('selected', 'selected');
});
});
Also, if I might recommend that you rename your country_cities model to just City. Imagine classes as a proper Entity, like Car or Person or Computer. Let me know if this works for you, as I tried to transcribe it from one of my own files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With