Django - Override data content of a django-tables2 LinkColumn

风流意气都作罢 提交于 2020-01-14 22:42:52

问题


I use django-tables2 LinkColumn to create a column that call a function that allow the export of the object in the table.

forms.py:

class FilesTable(tables.Table):
    id = tables.LinkColumn('downloadFile', args=[A('pk')], verbose_name='Export')

I would like the content of this column to be the href to downloadFile function with: Export as the text, not the id.


回答1:


Something like that should be working (warning I don't have Python here so it's not tested but you'll get the idea):

class CustomTextLinkColumn(LinkColumn):
  def __init__(self, viewname, urlconf=None, args=None, 
    kwargs=None, current_app=None, attrs=None, custom_text=None, **extra):
    super(CustomTextLinkColumn, self).__init__(viewname, urlconf=urlconf, 
      args=args, kwargs=kwargs, current_app=current_app, attrs=attrs, **extra)
    self.custom_text = custom_text


  def render(self, value, record, bound_column):
    return super(CustomTextLinkColumn, self).render(self, 
      self.custom_text if self.custom_text else value, 
      record, bound_column)    

And then you can use it like

id = CustomTextLinkColumn('downloadFile', args=[A('pk')], 
  custom_text='Export', verbose_name='Export', )

Of course you could always use a TemplateColumn or add a render_id method to your FilesTable but definitely the CustomTextLinkColumn is the most DRY method :)




回答2:


I can't comment, so I need to add another answer. I will correct that the "render" invocation should not have "self" in the parameter list.

class CustomTextLinkColumn(LinkColumn):
  def __init__(self, viewname, urlconf=None, args=None, 
    kwargs=None, current_app=None, attrs=None, custom_text=None, **extra):
    super(CustomTextLinkColumn, self).__init__(viewname, urlconf=urlconf, 
      args=args, kwargs=kwargs, current_app=current_app, attrs=attrs, **extra)
    self.custom_text = custom_text


  def render(self, value, record, bound_column):
    return super(CustomTextLinkColumn, self).render( 
      self.custom_text if self.custom_text else value, 
      record, bound_column)   

Use, as Serafeim says:

id = CustomTextLinkColumn('downloadFile', args=[A('pk')], 
  custom_text='Export', verbose_name='Export', )


来源:https://stackoverflow.com/questions/16198701/django-override-data-content-of-a-django-tables2-linkcolumn

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