Reputation: 357
I am trying to create a dependent dropdown list of countries and cities, based on the country selected I want to have another drop-down of cities in that country. In my Django model without creating models for country and city.
Here is my code:
models.py
from django.db import models
from django_countries.fields import CountryField
from partial_date import PartialDateField
class School(models.Model):
school_name = models.CharField(max_length = 30)
school_country = CountryField()
school_city = ??
school_population = models.IntegerField()
school_description = models.TextField(max_length = 300)
year_build = PartialDateField()
total_branches = models.IntegerField()
school_fees = models.IntegerField()
school_images = models.FileField(default=None)
def __str__(self):
return self.school_name
I was able to get countries using django-countries school_country = CountryField()
but I have no idea how to do the same for cities. I looked at django-cities but I didn't understand how to use it
Upvotes: 0
Views: 1421
Reputation: 1153
This is a Python's question, not a Django related thing.
You just need a structure that answer's on your question. It could be a simple dictionary like this:
{
"USA": ["New York", "..."],
"Canada": ["Ottawa", ".."]
}
and you can store it in the separated file in the project.
So you can use .keys()
for countries list that you are supporting and you can use a specific country as a key to get cities' list.
If you need to show this scructure in the front-end, you can do it with 2 different ways:
Upvotes: 0
Reputation: 14
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field
from django.db import models
from django_countries.fields import CountryField
from partial_date import PartialDateField
SCHOOL_CITIES_CHOICES = (
("Newyork", "Newyork"),
("Dubai", "Dubai"),
("Arusha", "Arusha"),
("Nairobi", "Nairobi"),
("West papua", "West Papua"),
)
class School(models.Model):
school_name = models.CharField(max_length = 30)
school_country = CountryField()
school_city = models.CharField(
max_length = 20,
choices = SCHOOL_CITIES_CHOICES,
default = '1'
)
school_population = models.IntegerField()
school_description = models.TextField(max_length = 300)
year_build = PartialDateField()
total_branches = models.IntegerField()
school_fees = models.IntegerField()
school_images = models.FileField(default=None)
def __str__(self):
return self.school_name
Upvotes: 0