In my project, I am working on creating a client form where the country, province, and city are selected based on different models:
class Country(models.Model):
Country = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.Country
class Province(models.Model):
province = models.CharField(max_length=100, unique=True)
Country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='province', null=True)
def __str__(self):
return self.province
class City(models.Model):
city = models.CharField(max_length=100, unique=True)
Province = models.ForeignKey(Province, on_delete=models.CASCADE, related_name='city', null=True)
def __str__(self):
return self.city
The goal is to dynamically update the list of provinces when a country is selected, and similarly for cities. To achieve this, I have created URLs and written the following code in my views.py:
class GetProvincesView(View):
def get(self, request, *args, **kwargs):
country_id = request.GET.get('country_id')
provinces = Province.objects.filter(Country_id=country_id)
data = [{'id': province.id, 'name': province.province} for province in provinces]
return JsonResponse(data, safe=False)
class GetCitiesView(View):
def get(self, request, *args, **kwargs):
province_id = request.GET.get('province_id')
cities = City.objects.filter(Province_id=province_id)
data = [{'id': city.id, 'name': city.city} for city in cities]
return JsonResponse(data, safe=False)
Below is a snippet of the template, model, and form that I am using for the client creation:
(template, models, and form snippets go here)
However, an issue I am facing is that when selecting a country, the province field does not update as expected. I have checked the console and added console logs in my code, but no logs appear in Chrome developer tools.
I am using Cookiecutter. Could it be possible that the base.html standard layout is affecting the functioning of my scripts on the page?