bayman bayman - 1 year ago 72
Python Question

Django tables2 external link generation w/ custom parameters

I have a music related model with Artist and song Title fields and I'd like to add a column that provides a link to search Amazon's digital music store using the artist and title from the given row on a table using Tables2. Here is what I have but not sure how to add the Amazon column and provide the Artist and Title fields to the Amazon URL?

class Artist (models.Model):
name = models.CharField(max_length=100)

class Track (models.Model):
artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist")
title = models.CharField(max_length=100, verbose_name="Title")

class amazonColumn(tables.Column):

def render(self, value):
return mark_safe('{{artist}}-{{title}}', value) # not sure how to pass artist and title records

class TrackTable(tables.Table):

amazon = amazonColumn()

class Meta:
model = Track
attrs = {"class": "paleblue"}
fields = ('artist', 'title', 'amazon')

Answer Source

I would use format_html.

Furthermore, you'll need to add record as a parameter to the render function, which allows you access its other attributes:

class AmazonColumn(tables.Column):
    amazon_url = '<a href="{artist}-{title}">Amazon</a>'

    def render(self, record):
        return format_html(self.amazon_url,, title=record.title) 

You might have to set empty_values=() where you instantiate the AmazonColumn in your table.