Как я могу вызвать страны и города в моем выпадающем списке с этим форматом json
Как получить данные из json без id/заголовков. Я не могу получить данные для моего выпадающего выбора.
Вот что у меня есть на данный момент... (и я новичок в этом)
Json файл, который выглядит следующим образом:
{
"Afghanistan": [
"Herat",
"Kabul",
"Kandahar",
"Molah",
"Rana",
"Shar",
"Sharif",
"Wazir Akbar Khan"
],
"Albania": [
"Elbasan",
"Petran",
"Pogradec",
"Shkoder",
"Tirana",
"Ura Vajgurore"
],
"Algeria": [
"Algiers",
"Annaba",
"Azazga",
"Batna City",
....
register_1.html
{% csrf_token %}
<div class="col-md-6">
<div class="form-group">
<label for="inputStatus">Country</label>
<select id="place-country" class="form-control-sm custom-select">
<option selected disabled>Country</option>
{% for country_name in countries %}
<option value="{{country.name}}">Country</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputStatus">City</label>
<select id="place-city" class="form-control-sm custom-select" name="topic">
<option selected disabled>City</option>
</select>
</div>
</div>
views.py
from django.http import JsonResponse
import json
import urllib.parse
def get_cities_ajax(request):
country_data = 'profileusers/static/profileusers/json/countries.json'
url = country_data.urllib.parse.urlencode()
data = request.get(url).json()
print(data)
for name in data:
print(name)
if request.method == "POST":
country_name = request.POST['country_name']
try:
countries = countries.objects.filter(name = country_name).first()
cities = Topic.objects.filter(countries = countries)
except Exception:
data['error_message'] = 'error'
return JsonResponse(data)
return JsonResponse(list(cities.values()), safe = False)
Или если я должен использовать form.py, поскольку он предназначен для регистрации?
from django.http import JsonResponse
import json
import urllib.parse
class ProfileForm1(forms.ModelForm):
country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label='Country:')
city = forms.ModelChoiceField(queryset=City.objects.all(), empty_label='City:')
class Meta:
model = Profileuser
fields = [
# 'avatar',
'picture',
'title',
'company_name',
'country',
'city',
]
def get_cities_ajax(request):
if request.method == "POST":
country = request.POST['name'] # dont have id for countries
try:
countries = Country.objects.filter(name = country).first()
cities = City.objects.filter(countries = countries)
except Exception:
data['error_message'] = 'error'
return JsonResponse(data)
return JsonResponse(list(cities.values('name')), safe = False) # dont have value 'id' or 'title' for cities
urls.py
path('profileusers/static/profileusers/json/', views.get_cities_ajax, name="get_cities_ajax"),
Я не уверен, как я должен написать js скрипт в register_1.html...?
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
// Get JSON data for countries and cities dropdown
$("#place-country").change(function () {
const countryName = $(this).val(); // get the selected country ID from the HTML dropdown list
$.ajax({ // initialize an AJAX request
type: "POST",
url: '{% url "get_cities_ajax" %}',
data: {
'country_name': countryName, // add the country id to the POST parameters
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(),
},
success: function (data) { // `data` is from `get_cities_ajax` view function
let html_data = '<option value="">---------</option>';
data.forEach(function (data) {
html_data += `<option value="${data.name}">${data.name}</option>`
});
$("#place-city").html(html_data); // replace the contents of the topic input with the data that came from the server
}
});
});
</script>
Благодарю за помощь!