Chained filters on Country and City Fields

46 views
Skip to first unread message

maryam yousaf

unread,
Oct 11, 2021, 9:45:22 AM10/11/21
to Django users
Hello,

I have one model which is campaign tracking. In that mode, I have two Fk's country and city. Cities are linked with country as I am using chained filtering so, it is working fine on model level where user has to give inputs but I also have to provide two filters on web interface Country and City. In filters, I want to have this functionality that when user choose any specific country from the drop down filter then in Cities filter, only specific cities who belongs to the selected country should appear in drop down but currently, I am getting all the cities. Any help is appreciated.

See the code below.

models.py:
class CampaignTracking(models.Model):
campaign_tracking_id = models.AutoField(primary_key=True)
country = models.ForeignKey(Country, on_delete=models.PROTECT)
city = ChainedForeignKey(
City,
chained_field='country',
chained_model_field='country',
show_all=False,
auto_choose=False,
sort=True,
null=True,
blank=True,
on_delete=models.PROTECT
)
campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE)
campaign_category = models.ForeignKey(CampaignCategory, on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
start_date_pre_campaign_period = models.DateField()
end_date_pre_campaign_period = models.DateField()
start_date_post_campaign_period = models.DateField()
end_date_post_campaign_period = models.DateField()
history = HistoricalRecords()


Admin.py:
class CountryFilter(AutocompleteFilter):
title = 'Country'
field_name = 'country'


class CityFilter(AutocompleteFilter):
title = 'City'
field_name = 'city'

class CampaignTrackingAdmin(SimpleHistoryAdmin):
list_display = ('country',
'city',
'campaign_name',
'campaign_category',
'start_date',
'end_date',
'start_date_pre_campaign_period',
'end_date_pre_campaign_period',
'start_date_post_campaign_period',
'end_date_post_campaign_period',
)
list_filter = (CountryFilter,
CityFilter,
)

Current filter in django Web Interface:
Screenshot 2021-10-11 at 14.09.43.png

Ryan Nowakowski

unread,
Oct 15, 2021, 2:36:08 PM10/15/21
to django...@googlegroups.com
I assume you're using Django smart selects since you seem to be using chained foreign key. Here's the documentation on how to get this to work inside your own templates:

https://django-smart-selects.readthedocs.io/en/latest/usage.html#usage-in-templates
Reply all
Reply to author
Forward
0 new messages