django-tables2 - accessing values of other columns in a table class
-
22-04-2021 - |
문제
Let's assume I have the following table class:
class TestTable(tables.Table):
id = tables.Column()
description = tables.Column()
def render_description(self, value):
return mark_safe('''<a href=%s>%s</a>''' % (???, value))
Is it possible to access the value of the column "id" in the render method, so that I can build up a link which leads to the id but shows the text which depends on the 'description'-field?
Thanks in advance!
해결책
From a quick glance at the docs for render_FOO it looks like you can just do:
class TestTable(tables.Table):
id = tables.Column()
description = tables.Column()
def render_description(self, value, record):
return mark_safe('''<a href=%s>%s</a>''' % (record.id, value)
Not sure of the exact shape of a row record, so it might be record['id']
, the link to the docs should help with exploration...
다른 팁
@Darb Thank you, that option works perfectly. However I was wondering if there is any way to do this using accesors instead of hacking a text column to output html...
In my case I use
# tables.py
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
#...
class FieldTable(tables.Table):
allows__count = tables.LinkColumn(viewname=None, attrs={'td': {'class': 'leftA'}},
verbose_name='No. of Allowed values')
def __init__(self, *args, **kwargs):
super(FieldTable, self).__init__(*args, **kwargs)
def render_allows__count(self, value, record):
if value!=0:
a = reverse(viewname='dict:field_detail',
kwargs=
{'field_slug': record.slug,
'extract_slug': record.extract.slug,
'system_slug': record.extract.system.slug})
return mark_safe('<a href={}>{}</a>'.format(a, value))
However I would like to replace the mark_safe, for something that calls the accessor of allows__count and returns the reverse hyperlink and the value...
Anyway works for know