django tables2 create extra column with links

倾然丶 夕夏残阳落幕 提交于 2019-11-30 15:12:00
lanzz

The problems you've encountered are caused by LinkColumn expecting to be bound to a specific attribute in your Item model, i.e. it is looking for an Item.edit attribute on your instances.

Since you don't actually have an Item.edit attribute, ordering over your edit column makes no sense, and you should mark it as non-orderable:

edit = tables.LinkColumn('item_edit', args=[A('pk')], orderable=False)

The text of the link itself would come from the value of the Item.edit attribute, which you don't have, so you will need to provide it yourself by adding a render_edit method to your table class:

def render_edit(self):
    return 'Edit'

You can replace the 'Edit' string with whatever you want displayed in that column.

Update: As suggested by @SunnySydeUp, you also need to specify empty_values=() for the column, in order to get its value rendered:

edit = tables.LinkColumn('item_edit', args=[A('pk')], orderable=False, empty_values=())

References:
http://django-tables2.readthedocs.org/en/latest/pages/order-by-accessors.html#specifying-alternative-ordering-for-a-column http://django-tables2.readthedocs.org/en/latest/pages/custom-rendering.html#table-render-foo-methods

Disclaimer: This answer is based on the django-tables2 documentation and source code, and hasn't been tested on an actual Django application.

To have the link properly formatted and with a link text of your choice, you can do the following in the table class:

def render_edit_link(self,record):
    return mark_safe('<a href='+reverse("edit", args=[record.pk])+'>Edit</a>')

Where 'edit' is the name of the url.

I create clickable links in extra columns with

edit = tables.LinkColumn('item_edit', text='Edit', args=[A('pk')], \
                         orderable=False, empty_values=())

It's not necessary to override the render method; the 'text' parameter changes the text of the link from 'none' to 'Edit', for example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!