Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django-smart-select

Tags:

django

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?

like image 626
blackmamba Avatar asked Apr 05 '15 17:04

blackmamba


1 Answers

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.

like image 194
onyeka Avatar answered Sep 18 '22 07:09

onyeka