Django 中的动态用户菜单 [英] Dynamic User Menu in Django

查看:22
本文介绍了Django 中的动态用户菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让用户菜单根据分配给用户所属用户组的权限而改变?我正在考虑在视图级别检查这些权限,并删除用户无权访问的菜单选项.

Is there a way to have a user menu that changes according to the permissions assigned to the user group a user belongs to? I am thinking of something that checks for these permissions at the view level, and also removes menu options a user does not have permission to.

推荐答案

是的,可以访问模板中的用户对象并检查用户是否是这样的员工:

Yes it is possible to access the user object in the template and check if the user is staff like this:

{% if user.is_staff %}
    <li>
        <a href="/admin/">Admin</a>
    </li>
{% endif %}

这将是一个示例,其中您的菜单中有 li 项链接.管理员链接只会为具有 is_staff 状态的用户呈现.使用 is_authenticated 也可以做到这一点.

This would be an example where your menu where li items of links. The admin link would only be rendered for users with is_staff status. The same could be done with is_authenticated.

Django 构建逻辑和表示分离,所以如果你想对菜单做一些更细粒度的控制,我建议在视图内部做逻辑,然后设置一个变量,你可以在模板来确定要显示的菜单.

Django is build to have logic and presentation separated, so if you want to do some more fine grained control of the menu, I would suggest doing the logic inside of the view, and then set a variable that you can check in the template to determine which menus to show.

这篇关于Django 中的动态用户菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆