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):

  

 

posted @ 2019-02-14 15:24  巨兽~墨菲特  阅读(631)  评论(0编辑  收藏  举报