Search code examples
djangodjango-urlsdjango-apps

Alias for app URI in Django project urls.py


My Django project "animals" has an app called "birds". In animals/urls.py the "birds" URIs are routed to birds/urls.py like this:

urlpatterns=[
    url(r'^birds/', include('birds.urls')),
    url(r'^b/',     include('birds.urls')), # alias
]

The "birds/" is the official, permanent base URI; "b/" is accepted as a shortcut/alias.

How can I have the "b/" URIs (permanently) redirected to "birds/", such that even though users can enter "b/penguin", the address bar of the browser will (ultimately) show "birds/penguin"? I prefer not to touch any code in the "birds" app, because it should not know (care) how the project maps URIs to the app.

I have tried to use

RedirectView.as_view(pattern_name='birds'))

but this results in a 410 Gone response. And

RedirectView.as_view(url='/birds/'))

redirects /b/penguin to /birds/, killing my bird.


Solution

  • You should try something like that:

    from django.views.generic import RedirectView
    
    urlpatterns=[
        url(r'^birds/', include('birds.urls')),
        url(r'^b/(?P<path>.*)$', RedirectView.as_view(url='/birds/%(path)s')),
    ]