i want make autofill form like this :
http://www.tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Overridding_Default_Select_Action.php
what i already know is to get list of cities form models :
views.py
def autofill(request):
if 'term' in request.GET:
qs = Citi.objects.filter(cities__icontains=request.GET.get('term'))
citys = list()
citys = [city.cities for city in qs]
return JsonResponse(citys, safe=False)
return render(request, 'part/test.html',)
jquery :
<script>
$(document).ready(function() {
var zipCode = { Chicago: 60290, California: 90001, Chennai: 600040,
Cambridge:02138 , Colombo:00800 };
$('#autoSuggest').autocomplete({
source: "{% url 'autofill' %}",
select: function(event, ui) {
$('#zipCode').val(zipCode[ui.item.value]);
}
})
});
</script>
Models.py
class City(models.Model):
cities = models.CharField(max_length=120)
zipcode = models.CharField(max_length=120)
def __str__(self):
return self.cities
while i still don't understand how to get zipCode data from models, and pair it with city ? Thanks
CodePudding user response:
You can use AJAX with Django to fetch city and zipcode without refresh the page like this :
"""your vieww.py that return a JSON response to the frontend"""
from django.http import JsonResponse
from .models import City
def city_zipcode(request):
"""Retrieve all cities objects and return only cities and zipcode"""
cities = City.objects.values('cities', 'zipcode')
"""Here w'll have an object like <QuerySet [{'cities': 'Chicago', 'zipcode': 60290}, ... ]>"""
# Transform this queryset to dict with cities and zipcode as Key/Pair
data_dict = {}
for dict in cities:
data_dict[dict['cities']] = dict['zipcode']
"""Here data_dict = {'Chicago': 60290, ...}"""
return JsonResponse(data_dict)
# urls.py
path('city_zipcode/', views.city_zipcode, name='city_zipcode'),
// javascript, this is in the template file (add this before the close body tag)
{% block javascript %}
<script>
async function getCities() {
// Django like url in JS
let url = '{% url 'city_zipcode' %}';
try {
// Get the backend JSON result
let results = await fetch(url);
return await results.json();
} catch (error) {
console.log(error);
}
}
// Call the function to get the cities paired with zipcode
let zipCode = await getCities();
// Here you can run your jQuery code
$(document).ready(function() {
// Use zipCode variable here, you can try to convert it to
// javascript dict before use it :
zipCode = JSON.parse(zipCode); // A javaScript object
});
</script>
{% endblock %}
CodePudding user response:
The other answer works too, but here's a method to do it without loading all zipcodes in memory, only the one that you need:
views.py
def get_zipcode(request, city_name):
city = get_object_or_404(City, cities=city_name)
return JsonResponse({zipcode: city.zipcode}, safe=False)
urls.py
path('get_zipcode/<str:city_name>/', get_zipcode, name='get_zipcode'),
js
<script>
$(document).ready(function() {
$('#autoSuggest').autocomplete({
source: "{% url 'autofill' %}",
select: async function(event, ui) {
let resp = await fetch(`/get_zipcode/${ui.item.value}/`);
let json = await resp.json()
$('#zipCode').val(json.zipcode);
}
})
});
</script>