如何授予django用户权限?

时间:2019-06-19 08:42:14

标签: django django-permissions

在这里,我试图给员工用户一些特定的权限。我这样尝试。这段代码将所有检查的权限保存在数据库表auth_user_user_permissions中,并在模板中显示特定用户的添加权限,但用户无法使用该权限。例如,我仅添加了user can view product的权限,并且此权限被添加到了表中,但是当我对此用户执行add product动作时,我可以执行甚至我都没有将此操作角色赋予该用户。

  

views.py

如果用户不是超级用户和职员,最初我会限制用户输入管理员url

class RestrictUserMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.find("/admin/") > -1:
           if not request.user.is_superuser and not request.user.is_staff:
              messages.error(request,'You have no permission to view this page')
              return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

        response = self.get_response(request)
        return response
  

settings.py

  middleware = 'app.views.RestrictUserMiddleware',
  

views.py

def update_user_roles(request,id):
     user = get_object_or_404(User, id=id)
     user_permissions = Permission.objects.all()

if request.method == 'POST':
    permissions = request.POST.getlist('user_permissions')
    print('hey',permissions)
    form = EditUserRole(request.POST or None,instance=user)
    if form.is_valid():
        role = form.save(commit=True)
        role.save()
        user.user_permissions.set(permissions)

        messages.success(request,'Roles updated for user '.format(user.username))
        return redirect('user_profile',user.id)
else:
    form = EditUserRole()
return render(request,'update_user_role.html',{'form':form,'user':user,'user_permissions':user_permissions})
  

add_product

def add_product(request):
    categories = Category.objects.all().order_by('-updated')
    if request.method == 'POST':
        form = AddProductForm(request.POST or None, request.FILES or None)

        if form.is_valid():
            product = form.save(commit=False)
            product.save()
            messages.success(request, '{} added.'.format(product.name))
            return redirect('add_product')
    else:
        form = AddProductForm()
    return render(request, 'add_product.html', {'form': form,
                                                    'categories': categories})
  

模板

<form action="{% url 'update_user_role' user.id %}" method="post" >
                        {% csrf_token %}

                        <div class="form-group">
                            <h5>User Roles</h5>
                               <div class="controls">
                         {% for permission in user_permissions %}
                         <input name ="user_permissions" type="checkbox" id="permission-{{permission.id}}"  value="{{permission.id}}" {% if permission in user.user_permissions.all %} checked="checked" {% endif %}>
                         <label for="permission-{{permission.id}}">{{permission.name}}</label>
                         {% endfor %}
                       </div>
                        </div>

                        <div>
                            <button type="submit" class="btn btn-info">Save</button>
                        </div>
                    </form>
  

forms.py

class EditUserRole(forms.ModelForm):
    class Meta:
        model = User
        fields = ['user_permissions']

1 个答案:

答案 0 :(得分:1)

就像我在评论中说的那样,Django并没有采取任何措施来强制执行管理员以外的权限(如何识别权限适用于哪种视图)?

您需要自己做;最简单的方法是使用permission_required decorator。例如:

@permission_required('products:change_product') # or whatever your permission is called
def update_user_roles(request,id):
    ...