【问题标题】:Creating name based user access to certain pages in the nav-bar在导航栏中创建基于名称的用户访问某些页面
【发布时间】:2022-01-14 06:36:01
【问题描述】:

我需要为我的 Django web-app 的某些功能创建基于用户的访问权限。

我已经想出了如何限制对非超级用户的访问:

{% if user.is_staff %}
<a href="{% url 'creditControlHome' %}">Credit Control</a>
{% endif %}

有没有办法根据名字做到这一点?

例如,“如果 user.name = George and Bill and Clint”那么他们可以看到导航栏的那部分?

【问题讨论】:

    标签: python django user-interface django-views django-templates


    【解决方案1】:

    有几种方法可以做到这一点。您可以为用户添加 auth Groups,然后检查该用户是否属于该组。例如,在您看来,您可以将用户添加到这样的组中:

    from django.contrib.auth.models import Group
    
    user_group = Group.objects.get_or_create(name='some_group_name') 
    user_group.user_set.add(user_obj)
    

    然后你可以使用自定义的templatetag来检查当前用户是否属于一个组:

    project_dir/app_name/templatetags/sometag.py

    from django import template
    
    register = template.Library() 
    
    @register.filter
    def has_group(user, group_name):
        return user.groups.filter(name=group_name).exists() 
    

    然后在你的模板中,你可以像这样使用这个模板标签:

    {% load sometag %}
    
    {% if request.user|has_group:"some_group_name" %} 
        <a href='#'>Your Link here</a>
    {% endif %}
    

    如果您不喜欢 templatetag 方法,您也可以过滤视图中的用户组,并将其用作标志以在模板中显示您的项目。

    如果这对您不起作用,那么您可以查看Permissions

    【讨论】:

      猜你喜欢
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多