How do I redirect by URL pattern in Django?

半腔热情 提交于 2020-01-11 05:35:15

问题


I have a Django based website. I would like to redirect URLs with the pattern servertest in them to the same URL except servertest should be replaced by server-test.

So for example the following URLs would be mapped be redirected as shown below:

http://acme.com/servertest/                        =>  http://acme.com/server-test/ 

http://acme.com/servertest/www.example.com         =>  http://acme.com/server-test/www.example.com

http://acme.com/servertest/www.example.com:8833    =>  http://acme.com/server-test/www.example.com:8833 

I can get the first example working using the following line in urls.py:

    ('^servertest/$', 'redirect_to', {'url': '/server-test/'}),

Not sure how to do it for the others so only the servetest part of the URL is replaced.


回答1:


Use the following (updated for Django 2.2):

re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),

It takes zero or more characters after servertest/ and places them after /server-test/.

Alternatively, you can use new path function that covers simple cases url patterns without using regex (and it is preferred in new versions of Django):

path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),



回答2:


It's covered in the docs.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

(Strong emphasis mine.)

And then their examples:

This example issues a permanent redirect (HTTP status code 301) from /foo/<id>/ to /bar/<id>/:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    ('^foo/(?P<id>\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}),
)

And so you see that it's just the nice straightforward form:

('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),



回答3:


Try this expression :

   ('^servertest/', 'redirect_to', {'url': '/server-test/'}),

or this one:
('^servertest', 'redirect_to', {'url': '/server-test/'}),



来源:https://stackoverflow.com/questions/9923178/how-do-i-redirect-by-url-pattern-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!