user/urls.py(在urlpatterns添加路由地址)
# 权限
path('add_user_perm/', add_user_perm),
path('u_index/', u_index, name='u_index'),
path('add_role/', add_role, name='add_role'),
path('add_perm/<int:id>/', add_perm, name='add_perm'),
path('menu/', menu, name='menu'),
path('add_user/', add_user, name='add_user'),
···
#user/views.py(定义路由的含义)
def add_user_perm(request):
if request.method == 'GET':
# 给用户添加权限
# 创建用户
user = Users.objects.create_user(username='coco',
password='123456')
# 分配权限
p = Permission.objects.filter(codename='add_change_user').first()
user.user_permissions.add(p)
return HttpResponse('给coco分配“添加和编辑用户权限”成功')
def u_index(request):
if request.method == 'GET':
users = Users.objects.all()
return render(request, 'users.html', {'users': users})
def add_role(request):
if request.method == 'GET':
groups = Group.objects.all()
return render(request, 'role.html', {'groups': groups})
if request.method == 'POST':
# 创建角色
role = request.POST.get('role')
Group.objects.create(name=role)
return HttpResponseRedirect(reverse('user:u_index'))
def add_perm(request, id):
if request.method == 'GET':
ps = Permission.objects.filter(codename__in=['add_users', 'change_users',
'delete_users', 'view_users',
'add_change_user', 'add_del_user']).all()
return render(request, 'perms.html', {'ps': ps})
if request.method == 'POST':
# 给角色添加权限
role = Group.objects.get(pk=id)
p_ids = request.POST.getlist('p')
for pid in p_ids:
per = Permission.objects.get(pk=pid)
# 角色添加权限
role.permissions.add(per)
return HttpResponseRedirect(reverse('user:u_index'))
def menu(request):
if request.method == 'GET':
user = Users.objects.get(username='coco')
request.user = user
return render(request, 'menu.html')
@permission_required('user.add_users')
def add_user(request):
if request.method == 'GET':
# user = Users.objects.get(username='coco')
# if 'user.add_users' in user.get_all_permissions():
# return HttpResponse('添加用户')
# else:
# return HttpResponse('你没有权限')
return HttpResponse('添加用户')