Home > Software design >  django admin specific redirects
django admin specific redirects

Time:01-11

I have a Django website where all urls are pointed to admin like this :

urls.py (Root)

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('', admin.site.urls),
]

I would like to know how to make specific redirects from one url to another, as I only have one model to manage and one app:

localhost/ => localhost/app/computer

localhost/app/ => localhost/app/computer

I tried adding this to urls.py but it does not work :

from django.http import HttpResponseRedirect

path('/', lambda request: HttpResponseRedirect('/app/computer/'))

I also thought of adding urls.py to app, but I think there might be a conflict as path('') will be on both urls.py, the root and the app

CodePudding user response:

I was able to implement this by using a custom RedirectMiddleware

settings.py

...
MIDDLEWARE = [
    ...
    'app.middleware.RedirectMiddleware',
]
...
ROUTES = [
    {'source': '/', 'destination': '/app/computer/'},
    {'source': '/app/', 'destination': '/app/computer/'}
]

middleware.py

from django.conf import settings
from django.shortcuts import redirect

def RedirectMiddleware(get_response):

    def middleware(request):
        response = get_response(request)
        path = request.path
        for route in settings.ROUTES:
            source = route['source']
            destination = route['destination']
            if path == source:
                return redirect(destination)
        return response

    return middleware

Not the best for sure, but it works for now, and any better suggestions will be greatly appreciated.

  •  Tags:  
  • Related