赞
踩
前言 :我这边使用002账号登录:其权限只有这几个:
只有查看和添加用户的权限,但是你看看我们这个网页中,
既然用户没有权限,为什么还要给别人选项,这不是给人心里添堵吗。所以我们需要进行细粒度权限 没有权限就不需要给别人显示这个选项。
细粒度权限控制 前面url的权限已经完善了,所以我们需要更细粒度的权限控制的时候就需要用到我们,进阶篇(二) 那时添加的表字段了,里面我们不是添加了一个action字段吗,添加进去肯定有添加的道理,在这一篇就要使用到了。
我们在中间件的代码中添加这一行:
我们把action相关的储存在我们新建的对象request.action中了,
首先我这边先说明一下,我们的action只有:list,add, edit, delete这四个,分别对应的是list = 查,add=添加 ,edit=编辑,delete=删除。
增删改查你可以自己自定义单词。我这边就是使用这几个来的。
现在我们需要进行使用request.action了。
首先我们在user界面进行细粒度权限控制:
views.py:
def user(request):
user_obj = User.objects.all()
id = request.session.get('user_id')
# 获取action
action = request.action
return render(request, 'user.html', {'user_obj': user_obj, 'action': action})
user.html:
{% extends 'base.html' %} {% block content %} <p><a href="/user/add/" class="btn btn-primary">添加用户</a></p> <table class="table table-bordered table-hover"> <thead> <tr> <th>序号</th> <th>名字</th> <th>操作</th> </tr> </thead> <tbody> {% for user in user_obj %} <tr> <td>{{ forloop.counter }}</td> <td>{{ user.name }}</td> <td> {% if 'edit' in action %} <a class="btn btn-info" href="">编辑</a> {% endif %} {% if 'delete' in action %} <a class="btn btn-danger" href="">删除</a> {% endif %} </td> </tr> {% endfor %} </tbody> </table> {% endblock %}
这样有权限的就会显示,没权限的就不显示。
然后我们把这个方法封装一下:
我先封装在views.py:
# 细粒度权限控制方法封装 class Per(object): def __init__(self, request): self.action = request.action def add(self): return 'list' in self.action def list(self): return 'add' in self.action def edit(self): return 'edit' in self.action def delete(self): return 'delete' in self.action def user(request): user_obj = User.objects.all() id = request.session.get('user_id') per = Per(request) return render(request, 'user.html', {'user_obj': user_obj, 'per': per})
user.html:
{% if per.edit %}
<a class="btn btn-info" href="">编辑</a>
{% endif %}
{% if per.delete %}
<a class="btn btn-danger" href="">删除</a>
{% endif %}
这就ok了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。