How to render button in Django base table?

31 Jul

How to render button in Django base table?

Assume that you have a table as defined below

class CustomerTable(BaseTable):
    pk = ToggleColumn()
    name = tables.LinkColumn('customers:customer', args=[Accessor('customer.id')])
    

    
    class Meta(BaseTable.Meta):
        model = Customer
        fields = ('pk', 'name',  'city', 'state' , 'phone')

Now assume you would like to display a button next to the phone

we can do it as below

class CustomerTable(BaseTable):
    pk = ToggleColumn()
    name = tables.LinkColumn('customers:customer', args=[Accessor('customer.id')])
    edit_button = tables.Column(empty_values=())

    
    class Meta(BaseTable.Meta):
        model = Customer
        fields = ('pk', 'name',  'city', 'state' , 'phone', 'edit_button')

    def render_edit_button(self, record):
        rendered_item = format_html(
            "<a href='{url}' class='btn btn-primary' role='button'>Edit</a>",
            url= reverse('users:user_edit', kwargs={'id':record.id})
        )
        return rendered_item

Leave a Reply

Your email address will not be published. Required fields are marked *