在我的 Django 项目中,我有由 Django 的内置身份验证系统创建的各种用户。每个用户都可以创建自己的App
模型实例。我想限制用户访问对象,以便用户只能查看他们创建的实例。为此,我创建了这个视图:
@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})
它有效,但我想知道是否有更普遍接受和/或安全的方法来做到这一点?