Login

Hyperlink read-only ForeignKey objects in admin to their change pages

Author:
strangefeatures
Posted:
January 23, 2012
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

If you set a ForeignKey field in the admin to read-only, you can use this snippet to automatically create a hyperlink to that object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django import template
from django.utils.safestring import mark_safe
from django.contrib.admin.util import lookup_field
from django.db.models.fields.related import ForeignKey
from django.db.models import ObjectDoesNotExist
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.contenttypes.models import ContentType

# see https://docs.djangoproject.com/en/1.2/howto/custom-template-tags/
register = template.Library()

@register.filter
def field_contents_foreign_linked(admin_field):
    """Return the .contents attribute of the admin_field, and if it
    is a foreign key, wrap it in a link to the admin page for that 
    object.
    
    Use by replacing '{{ field.contents }}' in an admin template (e.g. 
    fieldset.html) with '{{ field|field_contents_foreign_linked }}'.
    """
    fieldname = admin_field.field['field']
    displayed = admin_field.contents()
    obj = admin_field.form.instance
    try:
        fieldtype, attr, value = lookup_field(fieldname, obj, admin_field.model_admin)
    except ObjectDoesNotExist:
        fieldtype = None
    if isinstance(fieldtype, ForeignKey): #XXX - probably over-simplistic wrt escaping
        try:
            admin_url = get_admin_url(value)
        except NoReverseMatch:
            admin_url = None
        if admin_url:
            displayed = u"<a href='%s'>%s</a>" % (admin_url, displayed)
    return mark_safe(displayed)

@register.filter
def inline_form_contents_foreign_linked(inline_admin_form):
    """Return the .original attribute of the inline_admin_form, wrapped it in a link to the admin page for that 
    object.
    
    Use by replacing '{{ inline_admin_form.original }}' in an admin template (e.g. 
    tabular.html) with '{{ inline_admin_form|inline_form_contents_foreign_linked }}'.
    """
    obj = inline_admin_form.form.instance
    displayed = inline_admin_form.original
    try:
        admin_url = get_admin_url(obj)
    except NoReverseMatch:
        admin_url = None
    if admin_url:
        displayed = u"<a href='%s'>%s</a>" % (admin_url, displayed)
    return mark_safe(displayed)


#adapted from http://djangosnippets.org/snippets/1916/
def get_admin_url(obj):
    content_type = ContentType.objects.get_for_model(obj.__class__)
    return reverse(
      "admin:%s_%s_change" % (content_type.app_label, content_type.model), 
      args=[obj.pk])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.