限制用户访问页面

问题描述 投票:0回答:1

我希望用户只能看到自己的个人资料信息,而不能访问其他用户的信息。我正在使用 test_func 来检查尝试访问个人资料信息的用户登录是否是该信息的所有者。 问题是,由于某种原因它总是返回 true,当我转到我的页面并更改链接上的 id 尝试访问其他用户信息时,它会以某种方式自动使用用户应有的用户帐户登录,然后返回信息,它是,如果我以 id 1 的“lerton”身份登录,并且尝试访问 id 2 的用户“maguia”的信息,它会自动以“maguia”身份登录并返回“maguia”的信息

urls.py

path('profile/<int:pk>/', ProfileView.as_view(), name='profile'),

查看.py

class ProfileView(LoginRequiredMixin, DetailView, UserPassesTestMixin):
    model = get_user_model()
    template_name = 'profile.html'
    context_object_name = 'user'
    
    def test_func(self):
        user = self.get_object()
        return user == self.request.user

我尝试在 test_func 中比较用户的其他属性,如 id、用户名等,但没有成功

django restriction
1个回答
0
投票

您可以尝试以下代码来检查当前用户和给定用户是否相同:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import get_user_model
from django.views.generic import DetailView

class ProfileView(LoginRequiredMixin, DetailView):
    model = get_user_model()
    template_name = 'profile.html'
    context_object_name = 'user'

    def get_object(self, queryset=None):
        # Ensure that the user can only access their own profile
        obj = super().get_object(queryset)
        if obj != self.request.user:
            # If the user is trying to access someone else's profile, raise a 404 error
            raise Http404("You are not allowed to access this page.")
        return obj

或者您可以尝试调度方法:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import get_user_model
from django.views.generic import DetailView
from django.http import Http404

class ProfileView(LoginRequiredMixin, DetailView):
    model = get_user_model()
    template_name = 'profile.html'
    context_object_name = 'user'

    def dispatch(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj != self.request.user:
            raise Http404("You are not allowed to access this page.")
        return super().dispatch(request, *args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.