Relative redirect in Django
The url config of my app currently looks like this:
from django.conf.urls.defaults import patterns
from django.views.generic.simple import redirect_to
urlpatterns = patterns("myapp.views",
(r"^$", redirect_to, {"url": "main/"}),
(r"^(?P<title>.+)/$", "article"),
...
)
This works fine whe开发者_开发问答n the app’s urls are used without prefix.
Now, i want to include my app’s urls into a project’s url config with a prefix; like this:
urlpatterns = patterns("",
(r"^myapp/", include("myapp.urls")),
)
But then http://myserver.org/myapp/
isn’t redirected to http://myserver.org/myapp/main/
, but to http://myserver.org/main/
.
I think I understand how it works: The project’s url patterns get "myapp/"
. This matches the prefix, which is stripped away, leaving ""
, which is passed to the app’s patterns. The app is agnostic about the stripping and just redirects to main/
, which Django interprets as which doesn’t work for deeper nested urls (see edit below)./main/
How to tell Django to redirect to a URL relative to the app’s prefix?
Edit: Mistake!
Aah! Above code works fine, but my browser cached the permanent redirect to the previous url, which was "/main/"
. I cleared my cache and my new url "main/"
(which is now now temporary to prevent caching) Works just fine. Sorry!
But I realized that a answer would be helpful when I want to go to a url relative to the app’s root from a deeper nesting: "relative/"
may work for http://myserver.org/myapp/foo/
, but not for http://myserver.org/myapp/foo/bar/
.
In django 1.4 you will be able to use the function reverse_lazy()
:
from django.core.urlresolvers import reverse_lazy
urlpatterns = patterns("myapp.views",
(r"^$", redirect_to, {"url": reverse_lazy("myapp_title")}),
(r"^(?P<title>.+)/$", "article", name="myapp_title"),
...
)
reverse_lazy()
resolves to the URL which was given the same string as "name" parameter that is provided as an argument to reverse_lazy()
.
If you are working with an earlier version, that you will have to specify the full path, which, of course, violates the DRY principle:
(r"^$", redirect_to, {"url": "myapp/title/"}),
精彩评论