Avagut
Avagut

Reputation: 994

How to change display text in Django Tables 2 Link Column

I am using django tables 2 to list items and I am trying to add a column with a hyperlink to another page (an edit details page) with the selected row details using its primary key in the model.
I have used a link column as here which works(the link opens the expected page) but it is showing the itemid in the column while I want to put a link who's display text is marked "Edit". Can any help with how I can do that? I want to mimic the <a href="myurl"> Edit </a> behaviour

# tables.py
class MyItemsTable(tables.Table):
    itemid = tables.LinkColumn('myapp.views.edit_item', 
                        args=[A('pk')],orderable=False)
    class Meta:
        model = models.MyItems
        attrs = {"class": "paleblue"}

# views.py      
def myitems_list(request):
    myitems = models.MyItems.objects.all()
    table = tables.MyItemsTable(myitems)
    RequestConfig(request).configure(table)
    return render(request, 'myapp/mylist.html', {'table':table,'myitems':myitems})

def edit_item(request, pk):
    selecteditem = get_object_or_404(models.MyItems, pk=pk)
    return render(request, 'myapp/edit_item.html', {'selecteditem': selecteditem})

# models.py
class MyItems(models.Model):
    itemid = models.IntegerField(primary_key=True)
    itemfullname = models.TextField('Full Name',blank=True, null=True)

Upvotes: 1

Views: 2447

Answers (1)

DrBuck
DrBuck

Reputation: 942

You've probably solved this but there is a better way of adding custom text instead of using a TemplateColumn, and the functionality is actually already built in to a LinkColumn. To add your edit string:

# tables.py
class MyItemsTable(tables.Table):
    itemid = tables.LinkColumn('myapp.views.edit_item', 
                    args=[A('pk')], orderable=False, text='Edit')
class Meta:
    model = models.MyItems
    attrs = {"class": "paleblue"}

You can make the string dynamic to whatever you want using something like text=lambda record: 'edit-{0}'.format(record.name) for example. Have a look at the documentation .

Upvotes: 1

Related Questions