控制Django身份验证用户对特定对象实例的访问 [英] Controlling Django auth user access to specific object instances

查看:65
本文介绍了控制Django身份验证用户对特定对象实例的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django项目中,我有许多由Django的内置身份验证系统创建的用户。每个用户都可以创建自己的 App 模型实例。我想限制用户对对象的访问,以便用户只能查看他们创建的实例。为此,我创建了以下视图:

In my Django project, I have various users created by Django's built-in authentication system. Each user can create their own instances of the App model. I would like to restrict user access to objects such that users can only view the instances they have created. To do that I have created this 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})

它可以工作,但我想知道是否还有更多功能

It works, but I'm wondering if there's a more commonly accepted and/or safe way to do this?

推荐答案

这被称为行级权限,这是一个非常普遍的问题。请参阅此处以获取所有解决问题的应用。

This is called row-level permissions and it's a very common problem. See here for all the apps that solve it.

如果您只需要执行该特定测试,就选择像您这样的自定义解决方案(尽管由于它是样板,所以最好将其移至装饰器中)。否则,只需使用现有应用。

If that particular test is all you need to do, go for a custom solution like yours (though, since it's boilerplate, it's preferable to move it to a decorator). Otherwise, just use an existing app.

这篇关于控制Django身份验证用户对特定对象实例的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆