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

177
Views
Custom authentication middleware for specific routes in Django

I implemented a custom authentication setup for my Django project. There are some user roles for users. Now I want to ensure that some specific routs may acceptable only of specific user roles. Let's say the edit/uploaded-files can be acceptable only for the user with role = 1. So I created a middleware for that.

from django.shortcuts import redirect

class HRMiddleware(object):
    def process_request(self, request):
        user = request.user
        if not (user and user.is_authenticated() and user.email):
            return redirect('')
        if user.role_id.id != 1:
            raise 403
        return None

Now how can i apply this middleware for some specific routes only ? I found some solutions like using decorator @decorator_from_middleware(MyMiddleware) and specifying the routes in middle ware. Is there any better way to do this ? Actually I am a Laravel developer. This is my first Django project. In laravel we can specify the middlewares in the routes. Please help me

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try this:

URLS = ['/some_path/']

class HRMiddleware(object):
    def process_request(self, request):
        user = request.user
        if not (user and user.is_authenticated() and user.email) and request.path in URLS:
            return redirect('')
        if user.role_id.id != 1:
            raise 403
        return None
over 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!