Admin formfield_for_foreignkey is defeating me

14 views
Skip to first unread message

Mike Dewhirst

unread,
Jul 12, 2017, 4:42:23 AM7/12/17
to Django users
Would some kind person please point out where I'm going wrong with
formfield_for_foreignkey? (Admin code below)

It is not eliminating records with display = False from otherwise
available choices in a dropdown list as outlined below. Essentially, the
dropdown is showing everything.

The scenario is an index (list) of substances which are regulated by
different legislators in different jurisdictions and such regulations
expire and are renewed from time to time. In the Admin I want to prevent
expired regulations from being available for selection in a dropdown list.

To this end I have 'display = models.BooleanField(default=True)' on the
Regulation model (not shown*)

The Index_Regulation model (not shown*) has a foreign key to the Index
model (not shown*) and a foreign key to the Regulation model.


class IndexAdmin(admin.ModelAdmin):
""" Show an indexed substance in its own form """

def formfield_for_foreignkey(self, db_field, request, **kwargs):
""" restrict the regulation dropdown to displayable regs """

if db_field.name == "regulation":
kwargs["queryset"] = Regulation.objects.filter(display=True)

return super(IndexAdmin,
self).formfield_for_foreignkey(db_field, request, **kwargs)

readonly_fields = (('modified',))
fieldsets = (
('Indexed substance', {
'classes': ("wide",),
'fields': (
'name',
'modified',
),
}
),
)

class IndexRegulationInline(admin.StackedInline):
""" Show all regulations which apply to this indexed substance """

model = Index_Regulation
extra = 0
readonly_fields = (('modified',))
fieldsets = (
('Regulation detail', {
'classes': ('collapse', 'wide'),
'fields': (
'regulation', # foreign key to Regulation
'detail',
'modified',
),
}
),
)

inlines = ((IndexRegulationInline),)

admin.site.register(Index, IndexAdmin)


* Those models can be shown if necessary.

Thanks for any enlightenment.

Cheers

Mike



Reply all
Reply to author
Forward
0 new messages