I am new to Django and I am creating a web page that displays model information in a table format. I discovered a very useful library - django-tables2, which makes creating html tables very simple.
However, I cannot figure out how to set up the rendering of one of the columns in the table. In particular, I need a link column (I think it is implemented using LinkColumn or URLColumn in django_tables2) for rendering in
<a href="http://example.com">Personal Webpage</a>
instead of the django_tables2 path, where the default is the link name of the link.
<a href="http://example.com">http:
Where does this logic belong - in the model, in the view or in the template?
class Person(models.Model):
...
personal_webpage = models.URLField()
import django_tables2
import my_app.models import Person
class PersonTable(django_tables2.Table):
class Meta:
model = Person
from django.shortcuts import render
from django_tables2 import RequestConfig
from my_app.models import Person
from my_app.table import PersonTable
def personal_page_view(request):
table = PersonTable(Person.objects.all())
RequestConfig(request).configure(table)
return render(request, "my_app/personal_webpage.html", {"table": table})
{% load render_table from django_tables2 %}
<!doctype html>
<html>
...
<body>
...
{% render_table table %}
</body>
</html>
I have not studied the source code of django / django_tables2 yet, and hopefully some will have a suggestion.
UPDATE: I searched more for a solution, found a suggested solution:
class CustomTextLinkColumn(django_tables2.LinkColumn):
def __init__(self, viewname, urlconf=None, args=None,
kwargs=None, current_app=None, attrs=None, custom_text=None, **extra):
super(CustomTextLinkColumn, self).__init__(viewname, urlconf=urlconf,
args=args, kwargs=kwargs, current_app=current_app, attrs=attrs, **extra)
self.custom_text = custom_text
def render(self, value, record, bound_column):
return super(CustomTextLinkColumn, self).render(self,
self.custom_text if self.custom_text else value,
record, bound_column)
class PersonTable(django_tables2.Table):
webpage_link = CustomTextLinkColumn('my_app.views.personal_page_view', args=[A('personal_webpage')],
custom_text='Personal Webpage', verbose_name='Personal Webpage', )
. , " -", "---".