Skip to content

Commit

Permalink
Added fk display text
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 22, 2018
1 parent eb04678 commit f31fa65
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
Binary file added docs/fk_display.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions docs/fk_display.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,25 @@
How to change ForeignKey display text in dropdowns?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

:code:`Hero` has a FK to :code:`Catgeory`. In the dropdown, rather than just the name, you want to show the text "Category: <name>".

You can change the :code:`__str__` method on :code:`Category`, but you only want this change in the admin.
You can do this by creating a subclassing :code:`forms.ModelChoiceField` with a custom :code:`label_from_instance`.::


class CategoryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "Category: {}".format(obj.name)

You can then override :code:`formfield_for_foreignkey` to use this field type for category.::


def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'category':
return CategoryChoiceField(queryset=Category.objects.all())
return super().formfield_for_foreignkey(db_field, request, **kwargs)

Your admin look like this.


.. image:: fk_display.png
9 changes: 9 additions & 0 deletions heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ class Meta:
model = Hero
exclude = ["category"]

class CategoryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "Category: {}".format(obj.name)



@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
Expand Down Expand Up @@ -110,8 +115,12 @@ def children_display(self, obj):
# return []

def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'category':
return CategoryChoiceField(queryset=Category.objects.all())
return super().formfield_for_foreignkey(db_field, request, **kwargs)



def get_urls(self):
urls = super().get_urls()
my_urls = [
Expand Down

0 comments on commit f31fa65

Please sign in to comment.