Search code examples
pythondjangodjango-tables2

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?

models.py:

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")

tables.py:

class amazonColumn(tables.Column):

    def render(self, value):
        return mark_safe('https://www.amazon.com/gp/search?ie=UTF8&index=digital-music&keywords={{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')

Solution

  • 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="https://www.amazon.com/gp/search?ie=UTF8&index=digital-music&keywords={artist}-{title}">Amazon</a>'
    
        def render(self, record):
            return format_html(self.amazon_url, artist=record.artist.name, title=record.title) 
    

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