Last active
July 17, 2021 17:45
-
-
Save faulander/d83f2e1143a7161b76582fe5c5ab6cfe to your computer and use it in GitHub Desktop.
[Convert a foreign key field into clickable links] #python #django
This file contains hidden or 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
def linkify(field_name): | |
""" | |
Converts a foreign key value into clickable links. | |
If field_name is 'parent', link text will be str(obj.parent) | |
Link will be admin url for the admin url for obj.parent.id:change | |
""" | |
def _linkify(obj): | |
linked_obj = getattr(obj, field_name) | |
if linked_obj is None: | |
return "-" | |
app_label = linked_obj._meta.app_label | |
model_name = linked_obj._meta.model_name | |
view_name = f"admin:{app_label}_{model_name}_change" | |
link_url = reverse(view_name, args=[linked_obj.pk]) | |
return format_html('<a href="{}">{}</a>', link_url, linked_obj) | |
_linkify.short_description = field_name # Sets column name | |
return _linkify |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment