Login

True links in the admin list

Author:
svetlyak
Posted:
August 31, 2007
Language:
Python
Version:
.96
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months 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, 7 months ago

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.