redirect if not logged in django
# 1. Import necessary modules and functions
from django.shortcuts import redirect
# 2. Define a decorator function to check if the user is authenticated
def user_authenticated(view_func):
def _wrapped_view(request, args, *kwargs):
# 3. Check if the user is logged in
if request.user.is_authenticated:
# 4. If logged in, execute the original view function
return view_func(request, args, *kwargs)
else:
# 5. If not logged in, redirect to the login page
return redirect('login') # Replace 'login' with the actual URL or name of your login page
# 6. Return the wrapped view function
return _wrapped_view
# 7. Apply the decorator to a view function using the "@" syntax
@user_authenticated
def my_protected_view(request):
# 8. Code for the protected view goes here
return render(request, 'my_protected_template.html')
Replace 'login' with the actual URL or name of your login page. The user_authenticated
decorator checks if the user is logged in and redirects to the login page if they are not. The decorator is then applied to the my_protected_view
using the @
syntax. If the user is logged in, the original view function is executed; otherwise, they are redirected to the login page.