Home > database >  How to restrict access for personal profile page in django?
How to restrict access for personal profile page in django?

Time:03-15

For example, I have a user: testuser. His personal page is users/account/testuser. How can I restrict access for his personal profile page, so only he can visit this page and for others it will be 403?

I suggest I should use UserPassesTestMixin for it, but I don't know what to write in test_func. Actually I want to compare username from url, and user's username, and if it be equal, django will allow access to page. Or maybe there is another way to do it?

View:

class AccountInformationView(UserPassesTestMixin, DetailView):
    model = Profile
    template_name = 'users/account.html'

    def get_object(self, queryset=None):
        return get_object_or_404(User, username=self.kwargs.get('username'))

    def test_func(self):
        pass

url:

path('account/<str:username>', AccountInformationView.as_view(), name='account')

CodePudding user response:

you do not need test_func(...) you have just to pass pk=self.request.user.pk to the get_object.

this should work

class AccountInformationView(UserPassesTestMixin, DetailView):
    model = Profile
    template_name = 'users/account.html'

    def get_object(self, queryset=None):
        return get_object_or_404(User, username=self.kwargs.get('username'),pk=self.request.user.pk)
  • Related