Controlling Django auth user access to specific object instances

前端 未结 3 1148
无人及你
无人及你 2021-01-22 16:34

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

3条回答
  •  [愿得一人]
    2021-01-22 17:10

    There is a decorator called user_passes_test that restricts access to a view based on if the user passes a certain check

    from django.contrib.auth.decorators import login_required, user_passes_test
    
    @login_required
    @user_passes_test(lambda user: user.username == app.user.user.id)
    MyView(request):
        ...
    

    You can also add in an optional argument for a url to redirect to in the event they fail the check.

    Trying to do this from the admin page is also pretty easy, but takes a few extra steps.

    Docs Here

提交回复
热议问题