在我的Django項目中,我有各種由Django內置認證系統創建的用戶。每個用戶都可以創建自己的App
模型實例。我想限制用戶訪問對象,以便用戶只能查看他們創建的實例。要做到這一點我創建了這個觀點:控制Django auth用戶對特定對象實例的訪問
@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})
它的工作原理,但我想知道如果有一個更普遍接受和/或安全的方式來做到這一點?
不,它的罰款。 – freakish