Created
September 20, 2012 13:12
-
-
Save bmihelac/3755815 to your computer and use it in GitHub Desktop.
Django display link to change form for FK in list_display or readonly_fields
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
from django.core.urlresolvers import reverse | |
from django.contrib.contenttypes.models import ContentType | |
def edit_link(field_name, short_description=None): | |
""" | |
Displays link to change form for foreign key object. | |
Use in `readonly_fields` or `list_display`:: | |
class BookAdmin(admin.ModelAdmin): | |
readonly_fields = (edit_link('author', "Edit author"), ) | |
""" | |
def display_func(obj): | |
obj = getattr(obj, field_name) | |
if not obj: | |
return "" | |
ct = ContentType.objects.get_for_model(obj) | |
link = reverse('admin:%s_%s_change' % (ct.app_label, ct.model), | |
args=(obj.pk,)) | |
return u'<a href="%s">%s</a>' % (link, unicode(obj)) | |
display_func.allow_tags = True | |
if short_description: | |
display_func.short_description = short_description | |
return display_func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment