Задать вопрос

Тел: +7 965 3737 888

483

Просмотров

1

Ответов

True links in the admin list

<p>Usually, you can add links in the admin using such code:</p>
class Pingback(models.Model):
    #...
    target_uri = models.URLField( _('Target URI'))
    #...
    def admin_target(self):
        return '&lt;a href="%(targ)s"&gt;%(targ)s&lt;/a&gt;' % {'targ': self.target_uri}
    admin_target.short_description = _('Target URI')
    admin_target.allow_tags = True
    #...
    class Admin:
        list_display = ('id', 'admin_target')

<p>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:</p>
# Just add this line instead of the ugly four lines **def blabla**
admin_target = link('target_uri', _('Target URI'))

Вопрос полезен? Да0/Нет0
file_4765.py(207.0б)
None

Ответы (1):

Ответsvetlyak:31.08.2007
Ответ полезен? Да0/Нет0

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