Django: restrict user access to their own objects only

1.3k views Asked by At

I'm using @login_required to force users to authenticate before they create any object. but the problem is all authenticated user has access to update objects by object pk, even objects which created by other users.how can I limit user to access to their own objects only?

1

There are 1 answers

2
Satendra On

Firstly you need to keep user information in each object, so that you can distinguish between them.

If you have this information you just need to filter() your queryset to return objects related to loggedin user.

@login_required
def index_view(request):
   p = Model.objects.filter(user=request.user)
   return render(request, 'app/index.html', {'objects': p})

You will always get loggedin user object in request.user