I have Chart and Module models (see code below). Each chart belongs to a module (via a ForeignKey). A chart may have another chart as its parent (another ForeignKey). What I would like in the admin is that the dropdown for parent on a particular chart only includes charts in the same module.
I’m looking for a Python solution, not AJAX. That means that on creating a new chart the dropdown will have to be empty (without a model instance there’s no module selected) and that changing the module in the admin won’t update the parent options to match until the model is saved. I’m ok with that.
There are plenty of similar-sounding questions (and answers) that turn out to filter the options according to the user; ModelAdmin.formfield_for_foreignkey gets the request as an argument so you can use request.user, but it doesn’t get given a model instance to play with. (I’m using Django 1.3.)
My models (highly simplified of course):
class Module(models.Model):
pass
class Chart(models.Model):
module = models.ForeignKey(Module)
parent = models.ForeignKey(Chart, blank=True, null=True)
class ChartAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
# I would like to do this, but have no "instance":
kwargs['queryset'] = Chart.objects.filter(module=instance.module)
return super(ChartAdmin, self).formfield_for_foreignkey(self, db_field, request, **kwargs)
admin.site.register(Chart, ChartAdmin)
Just override the
ModelFormbeing used: