У меня есть 3 зависимых выпадающих списка проселочных дорог страны.
, где страна предварительно заполняется из базы данных и на основе выбора первого, во втором отобразятся соответствующие города.
проблема заключается в том, что после выбора пользователем из первого выпадающего списка система отображает следующую ошибку:
all_cities = selected_country.City_set.all () AttributeError: у объекта 'Country' нет атрибута 'City_set'
Я не знаю, как исправить эту ошибку.
models.py
class Country(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return str(self.name)
class City(models.Model):
name = models.CharField(max_length=100)
country = models.ForeignKey(Country,on_delete=models.CASCADE)
def __str__(self):
# return'id : {0} MouhafazatID :{1} Name :{2}'.format(self.id,self.MouhafazatID,self.name)
return str(self.name)
class Road(models.Model):
Vil = models.CharField(max_length=100)
city= models.ForeignKey(City,on_delete = models.SET_NULL, null=True)
country= models.ForeignKey(Country,on_delete = models.SET_NULL,null=True)
def __str__(self):
return str(self.Vil)
home2.html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('select#selectcountries').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var country_name = optionSelected.text();
data = {'cnt' : country_name };
alert(country_name);
$.ajax({
type:"GET",
url:'/getdetails',
// data:JSON.stringify(data),
data:data,
success:function(result){
console.log(result);
$("#selectcities option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>'+ result[i].name +'</option>');
};
},
});
});
});
</script>
</head>
<body>
<select name="selectcountries" id="selectcountries">
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="selectcities" id="selectcities">
</select>
<select name ="selectroads" id="selectroads">
</select>
</body>
</html>
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from testapp.models import *
import json as simplejson
def home2(request):
countries = Country.objects.all()
print("countries =", countries)
return render(request, 'home2.html',{'countries': countries})
def getdetails(request):
if request.method == 'GET' and request.is_ajax():
country_name = request.GET.get('cnt', None)
print ("ajax country_name ", country_name)
result_set = []
all_cities = []
answer = str(country_name[1:-1])
print('answer = ' ,answer)
selected_country = Country.objects.get(name=answer)
print ("selected country name ", selected_country)
all_cities = selected_country.City_set.all()
print("cities are: " , all_cities)
for city in all_cities:
print ("city name", city.name)
result_set.append({'name': city.name})
return HttpResponse(simplejson.dumps(result_set),content_type='application/json')
# return JsonResponse(result_set,status = 200)
else:
return redirect('/')
Как вы видите, я передаю данные в формате JSON.
, но функция в views.py выполняется до этой строки
print ("selected country name ", selected_country)
с правильным значением.
и затем отображается ошибка.