在django中,有没有一种方法可以限制用户访问一个url及其所有子url?

k10s72fa  于 2023-11-20  发布在  Go
关注(0)|答案(2)|浏览(106)

我正在写一个简单的Django应用程序。我有一个索引页面和帐户部分,只有当用户登录时才能看到帐户部分。
问题是,account部分有很多“子”网址,例如/accounts,/accounts/create,/accounts/update,/accounts/home等。
目前,我正在使用login_required装饰器和其他一些测试,但是当我在每个视图上编写mixin和装饰器时,代码看起来很混乱。
有没有一种简单的方法可以阻止一个用户的url及其所有子url?

urlpatterns = [
    path('',views.index_view,name="index"),

    url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html'
    ,form_class=forms.AuthenticationForm), name='login'),
    url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'),
    path('accounts/',views.SellerRegister.as_view(),name="register_seller"),
    path('accounts/address_create/',views.address_create,name="address_create"),
    path('accounts/register_buyer/',views.register_buyer,name="register_buyer"),

]

字符串

pgccezyw

pgccezyw1#

登录所需的装饰器应该在这里工作。

from django.contrib.auth.decorators import login_required

@login_required(login_url='/example url you want redirect/') #redirect when user is not logged in
def myview(request):
    do something
    return something #returns when user is logged in

字符串
您也可以直接在urls.py中使用装饰器

from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView

from .views import VoteView

urlpatterns = patterns('',
    (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
    (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
)


如果你正在使用CBV,你可以尝试使用Permission Mixins。

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

xkrw2x1b

xkrw2x1b2#

我还没有尝试过,但我可能会尝试用中间件来解决这个问题,简单地说:

settings.py

LOCKED_PATH = [
    'example/',
]

字符串

some_app/middleware.py

from django.conf import settings

class PathLockerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        print("Before view is called")
        uri = request.get_full_path()
        user = request.user
        is_authenticated = user.is_authenticated
        print("uri:", uri)
        print("user:", user)
        print("is_authenticated:", is_authenticated)
        # if the request.user is not authenticated and
        # the request.get_full_path() starts with one of the LOCKED_PATH in settings,
        # raise PermissionDenied()

        # else, view is called:
        response = self.get_response(request)

        print("After view is called")

        return response


当然,在settings.py的MIDDLEWARE中添加中间件。这只是一个快速的答案,我还没有尝试过。

相关问题