Search code examples
pythondjangodjango-authentication

Django login_required decorator with view based behavior


I have a url structure in in Django like this:

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

and my profile_view is like this:

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

I want to use login required decorator to only require login if account_id = None? So, if someone goes to /accounts/me URL, the system must require authenticated user. Otherwise, the page should be accessible.


Solution

  • One option would be to use the login_required decorator in the URL config:

    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')
    ]
    

    Then remove login_required from the profile_view itself.