[英]Conditional column display, django-tables2
I have developed a table, using django-tables2
which shows records of a model.我开发了一个表,使用
django-tables2
显示 model 的记录。 The last column of this table, is an "edit button" which leads user to the "edit page" of its row record.该表的最后一列是一个“编辑按钮”,它将用户引导到其行记录的“编辑页面”。
What I want is that the user can see the edit column
only if she has permission to edit the model!我想要的是用户只有在有权编辑模型的情况下才能看到
edit column
!
Also I need to mention that currently I'm using SingleTableView
to develop table view.另外我需要提一下,目前我正在使用
SingleTableView
来开发表格视图。
1: To make an entire column hidden , you can " exclude " that field from the table in the view. 1:要隐藏整个列,您可以从视图中的表中“排除”该字段。
class MyTableView(SingleTableView):
# class based view
model = MyModel
table_class = MyTable
def get_table(self, **kwargs):
table = super(MyTableView, self).get_table(**kwargs)
if not self.request.user.has_perm("can_edit"):
table.exclude = ('edit_button',)
return table
def my_table_view(request):
# function based view
table = MyTable(<queryset>)
if not request.user.has_perm("can_edit"):
table.exclude = ('edit_button',)
[...]
return render(request, template, context)
2: To hide the button in the column , you can check for permission before rendering the edit button by using a custom render function. 2:要隐藏列中的按钮,可以在渲染编辑按钮之前检查权限,使用自定义渲染function。
https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods
class MyTable(tables.Table):
edit_button = tables.Column()
def render_edit_button(self, record):
if request.user.has_perm("can_edit"):
url = reverse("edit_view", args=(record.id,))
return mark_safe(f'<a href="{url}">Edit {record.id}</a>')
return mark_safe("")
As I mentioned, I am using SingleTableView
.正如我所提到的,我正在使用
SingleTableView
。 So I found out there's a method in SingleTableView
class, which according to its docs:所以我发现
SingleTableView
class 中有一个方法,根据它的文档:
Allows passing customized arguments to the table constructor.
允许将自定义的 arguments 传递给表构造函数。
So to remove edit
column, I added this method in my view class (which was inherited from SingleTableView
:所以要删除
edit
列,我在我的视图 class 中添加了这个方法(它是从SingleTableView
继承的:
def get_table_kwargs(self):
if not self.request.user.has_perm('permission_to_edit'):
return {'exclude': ('edit_column',)}
else:
return {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.