Login

Snippets by overclocked

Snippet List

Limit ForeignKey filter values to those that have a relationship with current model

This is an updated snippet based on http://djangosnippets.org/snippets/2260/ The updated snippet can limit the filtering options for a foreign key field to only those entries that are related to the current model. I.e. if you have an Author model with a FK to Institution model, you can configure Author's changelist to include a filter on Institution, but only allow you to select institutions that have authors. Institutions that do not have authors won't show up on the list. To enable this, in your model's ModelAdmin class, set <fieldname>_fk_filter_related_only=True <fieldname>_fk_filter_name_field=<display this field of the related model in filter list> For example, in your AuthorAdmin class, you can do institution_fk_filter_related_only=True institution_fk_filter_name_field='name' Note that for the effect described above to work, you just need the last few lines of the big else clause in __init__, so if you don't care about filtering by FK property, you can just grab those few lines and create a simpler FilterSpec.

  • ForeignKey
  • Django-Admin
  • FilterSpec
Read More

overclocked has posted 2 snippets.