Django用户对Update对象的权限

时间:2019-03-27 07:17:52

标签: django object permissions modelform

工作流程如下

  • 用户发布一些内容。帖子的初始状态尚未发布(is_published = False)
  • 管理员批准该帖子。因此发布状态为已发布(is_published = True)
  • 发布状态为(is_published = True)的用户不是 能够编辑帖子。
  • 用户可以编辑,该帖子需要取消发布(is_published = False)。然后,用户可以编辑帖子。再次需要管理员批准。
def edit_post(request, post_id):
    if request.method == 'POST':
        # adminn start here
        if request.user.is_staff or request.user.is_superuser:
            obj = post.objects.get(pk=post_id)
            form = PostForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                post = form.save(commit=False)
                post.submitted = obj.submitted
                post.save()
                return redirect(approved_post)
            else:
                print("form invalid. post. admin")
                # admin end here
        #user star here
        else:
            obj = post.objects.get(pk=post_id)
            form = PostForm(request.POST, request.FILES, instance=obj)
            # check post status. if published cant edit
            if obj.is_published:
                print("no permission . user")
                return redirect(approved_post)  # error page here
            else:
                if form.is_valid():
                    post = form.save(commit=False)
                    post.submitted = request.user
                    post.save()
                    return redirect(approved_post)
                else:
                    print("form invalid. post. user")

    # GET
    else:
        obj = post.objects.get(pk=post_id)
        # checking is user is admin or normal user
        if not request.user.is_staff or not request.user.is_superuser:
            #checking if post is belong to the logged in user
            if obj.submitted == request.user:
                form = PostForm(instance=obj)
            else:
                print("not your object")
        else:
            form = PostForm(instance=obj)
    return render(request, 'post/edit_post.html', {'form': form})

我担心的是,有什么更好的方法来实现这一目标。

1 个答案:

答案 0 :(得分:0)

您要解决的问题是对象级权限。对于单个用例,您可以自己编写逻辑,但是我强烈建议使用外部程序包。

有两个众所周知且维护良好的软件包:

我相信django-rules最适合您的情况,并且实施起来非常简单。让我知道您是否需要示例。