I have thies in views.py
@login_required()
def dadmin(request):
I had not used @login_required() in dapost and dapage
And in url.py
url(r'^dadmin/$', dadmin, name='dadmin'),
url(r'^dadmin/post/$', dapost, name='dapost'),
url(r'^dadmin/page/$', dapage, name='dapage'),
Now I want is everytime when users try to access domain.com/dadmin/any... it redirect to login page. how ca i Do that? without placing @login_required() in dapost and dapage?
you can do it by using custom middleware
save this as custom_middleware.py file in your main app
from django.shortcuts import redirect
class CheckUser(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.user.is_authenticated() and \
request.path.startswith('/dadmin/'):
return redirect("/login/")
response = self.get_response(request)
return response
and in your settings.py edit the middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#custom middlewares
'app.custom_middleware.CheckUser'
]
If you set LOGIN_URL in your settings.py:
https://docs.djangoproject.com/en/1.8/ref/settings/#login-url
all anonymous users will be redirected when accessing to urls with login_required() decorator in their views.
Edit: you can make a custom LoginRequiredMiddleware too, with the path you desire.