2

I have the following models in Django, and using smart-selects:

class Country(models.Model):
    name = models.CharField(max_length=100)

class Province(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country)

class City(models.Model):
    name = models.CharField(max_length=100)
    country = models.ForeignKey(Country)
    province = models.ForeignKey(Province)

In the fixtures, i added multiple countries, with their provinces, and cities.

I'm using smart-selects for chaining in this model

class WorkArea(models.Model):
    work_area = models.CharField(max_length=100)
    country = models.ForeignKey(Country)
    province =  ChainedForeignKey(Province, chained_field="country",chained_model_field="country")
    city = ChainedForeignKey(City, chained_field=province", chained_model_field="province")

Now i have this model:

class Project(models.Model):
    project_name = models.CharField(max_length=100)
    province = models.ForeignKey(Province)

The question: In the model Project how do i show only provinces form Province model, that has country set to X (If i have countries "USA" and "Canada" i want the field province to show list of provinces in "USA" only, with preselecting country).

Ahmad Alzoughbi
  • 474
  • 1
  • 5
  • 14
  • I suppose you want that with Javascript so that when user select one country, all province of that country are automatically listed? – Ramast Feb 01 '16 at 16:58
  • No, in the model `Project` at the field `province` i want it to show list of USA provinces only. as you can see in the model `WorkArea` i already implemented the smart-selects plugin and it work perfect. my issue in the `Project` model, that i don't want the user to choose the country, it must be pre-selected as "USA" or pk=x, so there won't be `country` field in this model. – Ahmad Alzoughbi Feb 01 '16 at 17:12
  • I haven't used that package before, thanks for sharing. I have upvoted and stared your question, hopefully someone else can help – Ramast Feb 01 '16 at 22:34

1 Answers1

0

This is the solution using limit_choices_to

class Project(models.Model):
    project_name = models.CharField(max_length=100)
    province = models.ForeignKey(Province, limit_choices_to={"country": 1})
Ahmad Alzoughbi
  • 474
  • 1
  • 5
  • 14