Let's say I have the following model:
class Location(models.Model)
continent = models.CharField(max_length=20)
country = models.ForeignKey(Country)
I need to create a dependent dropdown so that when I select a continent I get all countries belonging to that continent. How should I do it?
Have you read the documentation? It's pretty straightforward. Depends on how you've got your continent/country set up. I'd recommend something like django-cities-light, which provides you with tables populated with countries/regions. I don't think it has continents though.
If you don't want to do that, you need to set up a Country model that has a column for Continent ID for example:
Continent(models.Model):
name = models.CharField()
Country(models.Model):
name = models.CharField()
continent = models.ForeignKey(Continent)
Then in the Location model set the fields thus:
from smart_selects.db_fields import ChainedForeignKey
Location(models.Model):
newcontinent = models.ForeignKey(Continent)
newcountry = ChainedForeignKey(
Country, # the model where you're populating your countries from
chained_field="newcontinent", # the field on your own model that this field links to
chained_model_field="continent", # the field on Country that corresponds to newcontinent
show_all=False, # only shows the countries that correspond to the selected continent in newcontinent
)
From the docs:
This example asumes that the Country Model has a continent = ForeignKey(Continent) field.
The chained field is the field on the same model the field should be chained too. The chained model field is the field of the chained model that corresponds to the model linked too by the chained field.
Hope that makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With