I ended up implementing it as validation on the admin form in the clean()
method.
ForeignKey dependencies in Django admin
-
20-07-2023 - |
Question
I'm using Django 1.6.4.
I have a Section
model that has a ManyToMany relationship with a TimePeriod
model. I also have a Question
model that has a ForeignKey relationship with the Section
model and the TimePeriod
model.
What I'd like to do is auto-filter the Section
part of the Question
form to valid Sections
when a given TimePeriod
is selected.
For example, if the 2014 TimePeriod
contains Section1 and Section2, but the 2013 TimePeriod
contains Section2 and Section3, I only want to display Section2 and Section3 in the Section
dropdown when 2013 is selected and Section1 and Section2 when 2014 is selected.
First, are there any packages that have been created that do this out of the box? If not, what do I have to do to set this up manually?
Thanks!
Model definitions were requested. They're pretty simple:
section.py
class Section(TimeStampedModel):
class Meta:
app_label = 'nps'
ordering = ('number',)
name = models.CharField(max_length=255)
number = models.IntegerField()
time_period = models.ManyToManyField('TimePeriod',
related_name='sections')
timeperiod.py
class TimePeriod(TimeStampedModel, TimeFramedModel):
class Meta:
app_label = 'nps'
name = models.CharField(max_length=40)
question.py
class Question(TimeStampedModel):
class Meta:
app_label = 'nps'
unique_together = ('time_period', 'number',)
time_period = models.ForeignKey('TimePeriod',
related_name='questions')
section = models.ForeignKey('Section', related_name='questions')
page = models.IntegerField()
number = models.CharField(max_length=20)
name = models.TextField()
slug = models.SlugField(editable=False)
Solution