Question

Need a little help with my urls.py and other stuff.

How can I replicate this in Django?

1) When user requests a non-existent page it will redirect to one up the directory level. Ex: example.com/somegoodpage/somebadpage should be redirected to example.com/somegoodpage.

2) When user requests page example.com/foo/bar/?name=John it will make url to example.com/foo/bar/name=John

3) When user requests page example.com/foo/bar/John it will change url to example.com/foo/bar/name=John.

Any help is greatly appreciated. Thank You.

Was it helpful?

Solution

For 1), if you don't want to do a separate route for every single route on your website, you'll need middleware that implements process_exception and outputs an HttpResponseRedirect.

For 2 and 3, those are rules that are presumably limited to specific routes, so you can do them without middleware.

2 might be doable in urls.py with a RedirectView, but since the relevant bit is a query string argument, I would probably make that an actual view function that looks at the query string. Putting a ? character in a url regex seems strange because it will interfere with any other use of query strings on that endpoint, among other reasons.

For 3, that's a straightforward RedirectView and you can do it entirely in urls.py.

OTHER TIPS

according to django doc for number 1:
django URL dispatcher runs through each URL pattern, in order, and stops at the first one that matches the requested URL, so add a pattern that matches "somebadpage"s and assign it to a view which redirects the user to "somegoodpage".

for number 2:
the doc says "The URLconf searches against the requested URL, as a normal Python string.
This does not include GET or POST parameters, or the domain name."
so i don't think that you can get the "?name=John" in url dispather, so if you describe what you want to do maybe I can help better
and for 3:
to capture bits of the URL and pass them as positional arguments to a view you should use named regular-expression groups, for example :

url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', 'news.views.month_archive'), 

and the request to /articles/2005/03/ would call the function news.views.month_archive(request, year='2005', month='03'), instead of news.views.month_archive(request, '2005', '03'). hope this helped :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top