Thomas Lewin
Thomas Lewin

Reputation: 71

django-tables2 exporting custom URL column

G'day All,

Hope everyone is doing well.

I have a table that I render with a custom column that is a hyperlink.

The problem is when i export to CSV it just gives me the text of the hyperlink and not the hyperlink.

I'm wanting to export the hyperlink instead of just the text, is this possible? (if i need to switch to xlsx export that's also fine) (worse comes to worse I can just make the text the full path)

Custom column:

document_link = tables.TemplateColumn('<a href="{{record.document_file.url}}/" target="_blank">{{record.document_file}}</a>', verbose_name="Document location")  

Thanks in advance,

Upvotes: 0

Views: 561

Answers (2)

Thomas Lewin
Thomas Lewin

Reputation: 71

This was the final way how I managed to do it:

class DocumentTable(ExportMixin,tables.Table):

    document_link = tables.TemplateColumn('<a href="{{record.document_file.url}}/" target="_blank">{{record.document_file}}</a>', verbose_name="Document location", exclude_from_export=True)  
    document_URL = tables.TemplateColumn('render_replaces_this',visible=False)
    
    def render_document_URL(self, value, record):
        return format_html(
            '{}{}',
            self.request.META['HTTP_HOST'],
            record.document_file.url,
        )

Upvotes: 0

Ben
Ben

Reputation: 2557

I would suggest making use of "Including and Excluding Columns" https://django-tables2.readthedocs.io/en/latest/pages/export.html#including-and-excluding-columns

Add exclude_from_export=True to the document_link field, and an invisible document_link_for_csv field.

class DocumentTable(tables.Table):

    document_link = tables.TemplateColumn(
        '<a href="{{record.document_file.url}}/" 
        target="_blank">{{record.document_file}}</a>', 
        verbose_name="Document location", 
        exclude_from_export=True
    )
    document_link_for_csv = columns.Column(
        visible=False, 
        accessor="document_file__url"
    )

Update based on comment: You can pass the request through to the table, and then do a custom render and request.build_absolute_uri().

class DocumentTable(tables.Table):

    document_link = tables.Column(
        verbose_name="Document location", 
        exclude_from_export=True
    )
    document_link_for_csv = columns.Column(
        visible=False, 
        accessor="document_file__url"
    )

    def render_document_link_for_csv(self, value, record):
        return format_html(
            '<a href="{}/{}/" target="_blank">{}</a>,
            request.build_absolute_uri(),
            record.document_file.url,
            record.document_file
        )

Upvotes: 1

Related Questions