0

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.

Gasim
  • 7,615
  • 14
  • 64
  • 131
  • 1
    The `@login_required` decorator will not help you with this. You should add a manual test to the view function itself. – Klaus D. Sep 20 '18 at 13:00
  • Then, after the test, do I just redirect or do I throw an exception and the auth system redirects properly? – Gasim Sep 20 '18 at 13:02
  • 1
    https://stackoverflow.com/questions/4356842/how-do-i-return-a-401-unauthorized-in-django – Klaus D. Sep 20 '18 at 13:04

1 Answers1

1

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516