zoukankan      html  css  js  c++  java
  • django 权限管理permission

    1.为模型类添加权限

    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    
    
    class Monitor(models.Model):
        ......
        
        class Meta:
            verbose_name = _(u'设备信息')
            verbose_name_plural = verbose_name
            db_table = 'monitor'
            permissions = (
                ('can_import_device', _(u'批量导入设备')),
                ('can_browse_monitor', _(u'浏览设备列表')),
            )

    2.views中可以使用如下方法来操作权限

    print request.user.has_perm('appname.can_import_device')  #appname为应用名,后面的为权限名
    myuser.user_permissions = [permission_list]   #myuser为通过request.user获取的user对象
    myuser.user_permissions.add(permission, permission, ...)
    myuser.user_permissions.remove(permission, permission, ...)
    myuser.user_permissions.clear()

    3.在template中使用权限方法:

    {% if perms.appname %} <!--appname为应用名-->
        <p>你有些权限可以操作</p>
        {% if perms.appname.can_import_device %}
            <p>你可以导入设备</p>
        {% endif %}
        {% if perms.appname.can_browse_monitor %}
            <p>你可以浏览设备!</p>
        {% endif %}
    {% else %}
        <p>无权限.</p>
    {% endif %}

    4.permission提供的装饰器

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def my_view(request):
        # ...
    
    def user_can_import(user):
        return user.is_authenticated() and user.has_perm("appname.can_import_device")
    
    @user_passes_text(user_can_import, login_url="/login/")
    def vote(request):
        # Code here can assume a logged-in user with the correct permission.
        ...
    
    from django.contrib.auth.decorators import permission_required
    
    @permission_required('appname.can_browse_monitor', login_url="/login/")
    def browse_monitor(request):
  • 相关阅读:
    MVB设备分类
    MVB帧
    也说析构---C++
    oracle中以dba_、user_、v$_、all_、session_、index_开头
    查看Oracle的表中有哪些索引(用user_indexes和user_ind_columns)
    Spark_总结五
    Spring编程式和声明式事务实例讲解
    缓存穿透,缓存击穿,缓存雪崩解决方案分析
    redis持久化2
    redis的持久化方式
  • 原文地址:https://www.cnblogs.com/wangmin0216/p/5942400.html
Copyright © 2011-2022 走看看