Search code examples
djangodjango-modelsdjango-tables2

Django-tables2 add html attribute to column


I have an Imagefield in a model, in my table that field is displayed as a link but when you click on it, it directs to a the url and instead I want to do download it. I foud that in html you can add the "download" attribute like this:

<a href="/media/pictures/CFE.JPG" download></a>

so in my django-tables2:

tables.py

class PagosDetailTable(tables.Table):

    imagen = tables.Column(
        attrs={"td": {"href": "download"}})

    class Meta:
        model = Pagos
        template_name = "django_tables2/bootstrap-responsive.html"
        fields = ('carro', 'semana', 'fecha', 'pago', 'imagen')
        attrs = {"class": "table table-hover table-sm"}

but that it overrides the href:

<a href="download"></a>

is there a way to append the download attribute using the tables.Column?


Solution

  • I found a workaround for my issue:

    tables.py

    class ImageColumn(tables.Column):
        def render(self, value):
            return format_html('<a href="/media/{}" download>Imagen</a>', value)
    
    
    class PagosDetailTable(tables.Table):
        imagen = ImageColumn()
    
        class Meta:
            model = Pagos
            template_name = "django_tables2/bootstrap-responsive.html"
            fields = ('carro', 'semana', 'fecha', 'pago')
            attrs = {"class": "table table-hover table-sm"}