工作流程如下
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})
我担心的是,有什么更好的方法来实现这一目标。
答案 0 :(得分:0)
您要解决的问题是对象级权限。对于单个用例,您可以自己编写逻辑,但是我强烈建议使用外部程序包。
有两个众所周知且维护良好的软件包:
我相信django-rules最适合您的情况,并且实施起来非常简单。让我知道您是否需要示例。