Dynamic User Menu in Django

2019-04-10 06:37发布

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.

2条回答
叛逆
2楼-- · 2019-04-10 07:04

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 %}

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 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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-10 07:18

For the most part, django's admin already doesnt give you links to things you can't do.

Django grappelli (a django admin skin) implements some sort of bookmarking, if that is what you mean http://code.google.com/p/django-grappelli/

查看更多
登录 后发表回答