-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters