How do I redirect by URL pattern in Django?

穿精又带淫゛_ 提交于 2019-12-01 05:27:39
Simeon Visser

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'}),

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'}),

Try this expression :

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

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

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