How to use django-smart-select
Solution 1
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.
Solution 2
- pip install django-smart-selects
Add smart_selects to your INSTALLED_APPS
Bind the smart_selects urls into your project's urls.py. This is needed for the Chained Selects and Chained ManyToMany Selects. For example
Your Models Models
Index.html Index
Related videos on Youtube
blackmamba
Updated on June 23, 2022Comments
-
blackmamba almost 2 years
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?