【问题标题】:How to display User Permission in Django template如何在 Django 模板中显示用户权限
【发布时间】:2018-03-29 05:01:40
【问题描述】:

所以我目前在创建 Django 用户时设置了一些用户权限。

我想显示所有用户的表格以及有关他们的信息,例如用户名、密码权限等。

执行此操作的代码与此类似。

<table id='usersTable'>
                    <tr>
                        <th></th>
                        <th>Status</th>
                        <th>Username</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Last Login</th>
                        <th>Expiry Date</th>
                        <th>Permission</th>
                    </tr>
                    {% for user in userlist %}
                    <tr id='{{ user.id }}' class='user-row urow'>
                        <td>
                            <input type="checkbox" name="check" class='userSelection'>
                        </td>
                        <td>
                            <div class="status"></div>
                        </td>
                        <td>{{user.username}}</td>
                        <td>{{user.first_name}}</td>
                        <td>{{user.last_name}}</td>
                        <td>{{user.email}}</td>
                        <td>{{user.last_login}}</td>
                        <td>{{user.userprofile.date_expiry}}</td>
                        {% load user_perm %}
                        <td>
                            {% if user|check_permission:'2018_map_view' %}
                               I have 2018 access
                            {% endif %}
                            {% if user|check_permission:'2017_map_view' %}
                               I have 2017 access
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </table>

我在底部尝试了在表格中显示每个用户权限的代码,但它似乎不起作用。

我的模板标签代码看起来像这样

from django.template import Library

register = Library()

@register.filter()
def check_permission(user, permission):
        permission = user.has_perm(permission)
        print(permission)
        return user.has_perm(permission)

我认为问题出在 userList 中的用户内部,并且在遍历所有用户时遇到问题,但我不确定如何解决此问题。任何现场将不胜感激。

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    这样做更好:

    从 django 导入模板 注册=模板.库()

    @register.filter()
    def check_permission(user, permission):
        if user.user_permissions.filter(codename = permission).exists():
            return True
        return False
    

    它以一种有效的方式检查权限是否存在,然后在模板加载标签内并使用它:

    {%load mytags%}  <!-- Assuming this is your tags.py file name -->
    
    {% if user|check_permission:'2018_map_view' %}
            ... do your staff ...
    {% endif %}
    

    【讨论】:

    • 谢谢@jsanchez,我以为我已经尝试过了,但我无法让它工作,我猜我搞错了!。
    • 我的荣幸@swilson0897
    猜你喜欢
    • 2014-05-23
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2018-10-04
    • 2017-09-10
    • 1970-01-01
    相关资源
    最近更新 更多