Django login_required装饰器具有基于视图的行为

时间:2018-09-20 12:53:35

标签: python django django-authentication

我在Django中有这样的url结构:

urlpatterns = [
    # ...
    path('me/', profile_view, name='my_profile'),
    path('<uuid:account_id>/', profile_view, name='user_profile')
]

我的个人资料视图如下:

@login_required
def profile_view(request, account_id=None):
    # ...

我想使用登录必需的修饰符仅在account_id = None时要求登录?因此,如果有人访问/accounts/me URL,则系统必须要求经过身份验证的用户。否则,该页面应该可以访问。

1 个答案:

答案 0 :(得分:1)

一种选择是在网址配置中使用login_required装饰器:

from django.contrib.auth.decorators import login_required

urlpatterns = [
    # ...
    path('me/', login_required(profile_view), name='my_profile'),
    path('<uuid:account_id>/', profile_view, name='user_profile')
]

然后从login_required本身中删除profile_view