check if the user is logged in django decorator
from django.shortcuts import redirect
def user_is_authenticated(view_func):
def wrapper(request, args, *kwargs):
if request.user.is_authenticated:
return view_func(request, args, *kwargs)
else:
return redirect('login') # Replace 'login' with the URL name of your login view
return wrapper
Usage in views:
from django.contrib.auth.decorators import login_required
from .decorators import user_is_authenticated
@user_is_authenticated
def your_view(request):
# Your view logic here
Note: The login_required
decorator provided by Django can also be used to achieve a similar result:
from django.contrib.auth.decorators import login_required
@login_required(login_url='login')
def your_view(request):
# Your view logic here
Both approaches achieve the same result, redirecting unauthenticated users to the login page. The first approach is a custom decorator, and the second one uses the built-in login_required
decorator. Choose the one that fits your preferences or requirements.