Carlitos_30
Carlitos_30

Reputation: 370

In Django, restrict user view using class based views

I have this url pattern:

path("user/<int:pk>", MyAccountView.as_view(), name='my_account'),

And this view:

class MyAccountView(DetailView):

    model = CustomUser

When the user is logged Django redirect to that URL.

The problem is that any user can access other users.

For example, if the logged user has pk 25, he can access the view of user with pk 26 by writing in the browser url box:

localhost:8000/user/26

I want that each user can access to his user page only, so if user with pk 25 try to access the url with pk 26, the access should be denied.

Can you point me in some direction of how this is done? The Django documentation is very confusing in this respect.

Thanks.

Upvotes: 0

Views: 250

Answers (2)

AshSmith88
AshSmith88

Reputation: 181

You need to override the get method of DetailView

from django.core.exceptions import PermissionDenied
from django.contrib.auth.mixins import LoginRequiredMixin

class MyAccountView(LoginRequiredMixin, DetailView):

    model = CustomUser

    def get(self, request, pk):
        if request.user.pk != pk:
            raise PermissionDenied()
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)
   

Upvotes: 3

Zkh
Zkh

Reputation: 593

Easy !

  1. First change the view path from user/<int:pk>/ to user/
  2. Link the view to the current user, DetailView won't work because it heavily relies on either pk or slug and we won't be using none of them, so you'll have to write a new view. (Example using FBV because i do not use CBV)
# views.py

from django.contrib.auth.decorators import login_required

# redirects to login page if the user is not authenticated
@login_required(login_url='/example url you want redirect/') 
def get_user_profile(request):
    context = dict(user=request.user)
    return render(request, "template.html", context)

And that's it, any user visiting /user/ will only see their account/profile.

Upvotes: 1

Related Questions