在我的 Django 项目中,我有由 Django 内置身份验证系统创建的各种用户。每个用户都可以创建自己的 App
模型实例。我想限制用户对对象的访问,以便用户只能查看他们创建的实例。为此,我创建了此 View :
@login_required
def appDetail(request, app_id):
try:
app = App.objects.get(pk=app_id)
# Testing if the currently logged in user is
# the same as the user that created the 'app':
if request.user.id == app.user.user.id:
if request.method == 'POST':
form = AppForm(request.POST, instance=app)
if form.is_valid():
edited_app = form.save()
return HttpResponseRedirect('/thanks/')
else:
form = AppForm(instance=app)
# If 'app' does not belong to logged in user, redirect to 'accessdenied' page:
else:
return HttpResponseRedirect('/accessdenied/')
except LeaveApp.DoesNotExist:
raise Http404
return render(request, 'AppDetail.html', {'form':form})
它有效,但我想知道是否有更普遍接受和/或更安全的方法来做到这一点?
最佳答案
这称为行级权限,这是一个非常常见的问题。请参阅here适用于所有解决该问题的应用程序。
如果您只需要执行该特定测试,请选择像您这样的自定义解决方案(不过,由于它是样板文件,因此最好将其移至装饰器)。否则,只需使用现有的应用程序。
关于django - 控制 Django auth 用户对特定对象实例的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16053122/