Search code examples
djangodjango-tables2

Link column with link to a file in static (django-tables2, Django)


I generate a table with django-tables within Django. I want to create a column with links to txt files in my static directory. When the user clicks on the link, the txt file should be displayed.

To create a link to the txt file within an html, I simply do:

<a href="{% static co.log %}">txtfile</a>

However, I have problems finding the right way to do this using django-tables. I tried to define the link column as follows:

logfiles = tables.LinkColumn('{static', text='txtfile', args=[A('log')], orderable=False, empty_values=())

This gives the error "Reverse for '{static' not found. '{static' is not a valid view function or pattern name."

I also tried this:

tables.py

logfiles = tables.LinkColumn('logfile', text='bla', orderable=False, empty_values=())

urls.py:

url(r'^logfile/', views.logfile, name='logfile')

views.py:

def logfile(request):
return HttpResponse('<p>yeah</p>')

So I can find a way to open a new url, but how to open a specific static file, i.e.how to pass the info from [A('log')], which is basically the filename?

Any help is appreciated.


Solution

  • You could use a TemplateColumn to achieve this:

    class LogTable(tables.Table):
        log = tables.TemplateColumn(
            template_code='{% load static %}<a href="{% static value %}">txtfile</a>'
        )
    

    Note that the column name is log, so there is no need to specify the accessor. If you want the color to appear with a different name, use the verbose_name kwarg.