2016-06-10 122 views
0

我正在使用Django-tables2渲染一个表格,该表格包含表格标签,以便保存修改后的行顺序数据。我需要让表格在窗体标签内部呈现下面的隐藏输入,以便表单可以保存修改过的数据。如何在django-tables2中为ID字段添加隐藏输入?

<input type="hidden" name="id" value="{{ track.id }}"> 

该解决方案可以正常工作,但它目前呈现td标签内的输入标签,这使得它显示ID列。如何在隐藏输入标签的同时隐藏ID列?

<td class="id">20098<input type="hidden" name="track_id" value="20098" /></td> 

tables.py:

class TrackIDColumn(tables.Column): 

    def render(self, value): 
     return mark_safe(str(value) + '<input type="hidden" name="track_id" value="' + str(value) + '" />') 

class PlaylistTable(tables.Table): 

    id = TrackIDColumn() 

    class Meta: 
     model = Track 
     attrs = {"class": "paleblue"} 
     orderable = False 
     fields = ('id', 'artist', 'title',) 

模板:

<form method='POST' action='{% url "playlists:save_playlist" username=user.get_username slug=playlist.slug %}'>{% csrf_token %} 
{% render_table table "django_tables2/bootstrap.html" %} 
<button type="submit" name="playlist_id" value="{{ playlist.id }}" class="btn btn-primary">Save</button> 
</form> 

回答

1

你不能呈现在列成才勿使列。你可以做的是对列添加一个空的verbose_name隐藏标题:

class PlaylistTable(tables.Table): 
    id = tables.Column(verbose_name='') 

    def render_id(self, value): 
     return format_html('<input type="hidden" name="track_id" value="{}" />', str(value)) 

如果你完全不想要一个额外的列被渲染,你必须隐藏输入标签添加到另一列:

class PlaylistTable(tables.Table): 
    artist = tables.Column() 
    title = tables.Column() 

    def render_title(self, value, record): 
     return format_html('{} <input type="hidden" name="track_id" value="{}" />', value, record.id)