Login

True links in the admin list

Author:
svetlyak
Posted:
August 31, 2007
Language:
Python
Version:
.96
Tags:
admin
Score:
6 (after 6 ratings)

Usually, you can add links in the admin using such code:

class Pingback(models.Model):
    #...
    target_uri = models.URLField( _('Target URI'))
    #...
    def admin_target(self):
        return '<a href="%(targ)s">%(targ)s</a>' % {'targ': self.target_uri}
    admin_target.short_description = _('Target URI')
    admin_target.allow_tags = True
    #...
    class Admin:
        list_display = ('id', 'admin_target')

But when you have two or more url fields, such approach becomes to expensive. Follow the DRY principe and use my code in such way:

# Just add this line instead of the ugly four lines **def blabla**
admin_target = link('target_uri', _('Target URI'))
1
2
3
4
5
6
def link(field, desc):
    def _link(self):
        return '<a href="%(url)s">%(url)s</a>' % {'url': getattr(self, field)}
    _link.short_description = desc
    _link.allow_tags = True
    return _link

More like this

Comments

svetlyak (on August 31, 2007):

I have modified this code slightly, and add maxlength argument, to make admin layout happy with very long urls:

def link_field(field, desc, maxlength = 40):
    def _link(self):
        url = getattr(self, field)
        if len(url) > maxlength:
            text = url[:maxlength/2-2] + '...' + url[-(maxlength/2-1):]
        else:
            text = url
        return '<a href="%(url)s">%(text)s</a>' % {'url': url, 'text': text}
    _link.short_description = desc
    _link.allow_tags = True
    return _link

#

Please login first before commenting.