Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
How to ask for login to access to any url django

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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'
]
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!