Django Redirect for All Pages

Question:

I have multiple pages in my Django project.

Here’s my urls.py

urlpatterns = [
    path('page1', views.page1),
    path('page2', views.page2),   
    path('page3', views.page3),  
]

I want to add a redirect that applies to all the pages so that users that aren’t authenticated will be redirected to MSOAuth2.

Here’s my views.py

def page1(request):
    return render(request, "page1.html")
 
def page2(request):
    return render(request, "page2.html")

def page3(request):
    return render(request, "page3.html")

def MS_OAuth2(request):
    if not request.user.is_authenticated:
        return redirect('https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?') 

What regex or url pattern do I need to use so all my pages can redirect to views.MS_OAuth2?

This is what I have so far but it’s not working. I want the redirect to apply to all pages in my website.

urlpatterns = [
    path('page1', views.page1),
    path('page2', views.page2),   
    path('page3', views.page3),  
    path(r'^$', views.MS_OAuth2)
]

Thank you!

Asked By: WAA1

||

Answers:

Try to read more about decorators:

loogin_required decorator:
https://docs.djangoproject.com/en/4.1/topics/auth/default/#the-login-required-decorator

user_passes_test decorator:
https://docs.djangoproject.com/en/4.1/topics/auth/default/#django.contrib.auth.decorators.user_passes_test

and, of course, try to read about Django-GCBV, this is aways better than functions.
https://docs.djangoproject.com/en/4.1/topics/class-based-views/

and

permission_required decorator:
https://docs.djangoproject.com/en/4.1/topics/auth/default/#django.contrib.auth.decorators.permission_required

In your case:

# in settings.py:
LOGIN_URL = 'https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?'

and in urls.py:

from django.colntrib.auth.decorators import login_required

urlpatterns = [
    path('page1', login_required(views.page1)),
    path('page2', login_required(views.page2)),   
    path('page3', login_required(views.page3))
]

or, if you don’t want to change urls.py:

#views.py
from django.colntrib.auth.decorators import login_required

@login_required
def page1(request):
    return render(request, "page1.html")
 
@login_required
def page2(request):
    return render(request, "page2.html")

@login_required
def page3(request):
    return render(request, "page3.html")

...  # your staff here
Answered By: Maxim Danilov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.