blackmamba
blackmamba

Reputation: 1992

How to use django-smart-select

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?

Upvotes: 8

Views: 13507

Answers (2)

joselitoo
joselitoo

Reputation: 59

  1. pip install django-smart-selects
  2. Add smart_selects to your INSTALLED_APPS

  3. Bind the smart_selects urls into your project's urls.py. This is needed for the Chained Selects and Chained ManyToMany Selects. For example

  4. Your Models Models

  5. Index.html Index

Upvotes: 6

onyeka
onyeka

Reputation: 1537

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.

Upvotes: 8

Related Questions