Created
October 24, 2018 07:57
-
-
Save mpyrev/c0837be219f27409ed875724c3b176a7 to your computer and use it in GitHub Desktop.
Replaces text representation of object with link to corresponding admin change page
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
import typing | |
from functools import wraps | |
from django.urls import reverse | |
from django.utils.html import format_html | |
def display_admin_link(admin_method: typing.Callable=None, *, display_function: typing.Callable=str): | |
""" | |
Returns link to corresponding admin change page of object | |
:param admin_method: method of admin class that should return object | |
:param display_function: function that should return text for link | |
""" | |
def decorator(func): | |
@wraps(func) | |
def decorated(*args, **kwargs): | |
obj = func(*args, **kwargs) | |
value = display_function(obj) | |
link = reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name), args=(obj.pk,)) | |
return format_html('<a href="{link}">{value}</a>', value=value, link=link) | |
return decorated | |
if admin_method: | |
return decorator(admin_method) | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment