我正在使用Django-tables2来呈现一个表,该表包含围绕表的表单标记,以便保存修改后的行顺序数据。我需要让表在表单标记内呈现以下隐藏的输入,以便我的表单可以保存修改后的数据。
<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>
答案 0 :(得分:3)
如果不渲染列,则无法在列中渲染某些内容。你可以做的是通过在列上添加一个空的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)