Redirection in Django URLs - django

How do I redirect all URLs starting from a particular pattern to another?
Description:
I want to be able to redirect as follows:
/pattern1/step1/ to /pattern2/step1/
/pattern1/step2/ to /pattern2/step2/
/pattern1/continue/ to /pattern2/continue/
What is the easiest way of doing this in Django URL patterns?

RedirectView works. Capture the remainder of the path with a named kwarg. It will be passed into RedirectView.get_redirect_url, so you can interpolate it into the url you provide.
url(r'^pattern1/(?P<url>.+)$', RedirectView.as_view(url="/pattern2/%(url)s")),
# ^ ^
# | this url appears here |

You can use redirect_to generic view and add redirection urls in urls.py as:
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
('^pattern1/step1/$', redirect_to, {'url': '/pattern2/step1/'}),
#any more patters.
)
Here is documentation: Generic view redirect_to . These can take the parameters as well.

Redirections could also be handled at the web server level.

Related

django url not working when directions followed

This is driving me crazy. Everything looks good. I am getting this error:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/home
Using the URLconf defined in gds.urls, Django tried these URL patterns, in this order:
^admin/
^fixiss/
The current URL, home, didn't match any of these.
Here is my root url:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^fixiss/', include('fixiss.urls')),
]
My app url:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name="index"),
]
And the view in my app:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Home page!")
Any help would be greatly appreciated!
Assuming your "app url" module is 'fixiss.urls' where you only have one pattern (the empty string) and you are you are including it under fixiss/, the only match should be:
http://localhost:8000/fixiss/
If you change your one pattern to:
url(r'^home$', views.home, name="index")
that view will be served under
http://localhost:8000/fixiss/home/
The actual name of the view function (home in this case) is rather irrelevant when it comes to url pattern matching. What counts is the specified regex pattern.
This is very well documented:
Django url dispatching in general
Including urls in particular
That is because no url matches home/. Your url should be http://localhost:8000/fixiss/
In the app's (fixiss) url file, the regex is empty meaning, it does not expect a string after fixiss/ in the url for it to match.

Django Page not found

I want to create urls to go to links like this: examples.com/baiviet/post-example/
*post-example is a slug
this is my root urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include('blog.urls')),
)
Then, this is my blog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from blog import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^baiviet/(?P<slug>)/$', views.view_post, name='viewpost'),
)
My views.py:
def view_post(request, slug):
getpost = get_object_or_404(Blog, slug=slug)
return render(request, 'view_post.html', {'post':getpost})
And my view_post.html:
{{ post.content }}
The only thing I have is "Page Not Found" Error. I have tried to solve it and it takes me 2 hours before posting this question. I hope that someone can help me solve this problem. Thanks you
The reason for 404 is that in your root urlconf, you have
url(r'^$', include('blog.urls'))
Here, $ indicates end of url pattern. Change that to
url(r'^/', include('blog.urls'))
# ^ note the $ shoudl be replaced by / when you are doing an include.
Here is the relevant documentation:
Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.include()), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
The issue with the missing pattern, as alecxe mentions on <slug> would arise after it resolves this issue (404).
EDIT:
For you to access the homepage, you need to have a trailing / or have the setting APPEND_SLASH setting to True. Since your URL Pattern is expecting a prefix of / - Now, if you dont want it, in your root urlconf, change r'^/' to just r'^'
You have an empty capturing group configured for the url:
url(r'^baiviet/(?P<slug>)/$', views.view_post, name='viewpost')
HERE ^
You need to provide a pattern for a slug to match, e.g. alphanumeric, underscore and a dash:
url(r'^baiviet/(?P<slug>[a-zA-Z0-9_-]+)/$', views.view_post, name='viewpost')

django url regular expressions capture invalid url

I want to understand how to create urls / regular expressions to capture and redirect to views those patterns that do not match any defined pattern.
I have a pattern in the url for the project where I am looking for waitlist.
I that does not match I want a to direct it to a project view, which I was assuming would be
caught by the second url below
url(r'^waitlist/', include('waitlist.urls')),
url(r'^.*$', views.my_default_2),
If the user does include the url for waitlist, then it should pass to the app url for a match
and if no match pass through to the wild card, the second line.
url(r'^$', views.index, name='index')
url(r'^.*$', views.my_default),
Is this the correct way to capture invalid/ incorrect url input through the project and the app?
For project you can override 404 view
https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
for default django raise exception when none found. but you can customize this for your need
You can use default page not found view
Follow this
project/waitlist/urls.py
from django.conf.urls import patterns, url
from waitlist import views
urlpatterns = patterns('waitlist.views',
url(r'^$', 'index', name='index'),
)
handler404 = 'mysite.views.my_custom_page_not_found_view'
project/waitlist/views.py
defaults.page_not_found(request, template_name='404.html')
For reference how defaults.page_not_found works see this link

Django basic url slugifying issues

I want to slugify my urls in my Django application. I have read many documents but I am still not sure how to do it better. I have two questions:
How to call the same view for two different urls?
I would like to call home view for both www.mysite.com and www.mysite.com/index.html
(r'^$', 'myapp.main.views.home')
(r'([-\w]+)$', 'myapp.main.views.home')
The code above sounds good but of course it raises an error as home view expects 1 parameter but 2 is given. How can I resolve this?
I have so many apps and they all have their own urls.py file. I was handle them as including their urls file to the root urls.py as
(r'^warehouse/', include('myapp.warehouse.urls')),
In that way, urls seems like www.mysite.com/warehouse/blabla/
However, I want to slugify them as www.mysite.com/warehouse_blabla.html
Slugifying is not hard but how can I resolve such url and redirect it to the blabla view in warehouse app?
Thanks
Regarding the first problem, you would be better off using a redirect for the index.html URL (better for SEO etc.)
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
url(r'^$', 'myapp.main.views.home')
url(r'^index.html$', redirect_to, {'url': '/'}),
)
Regarding the second issue, your urls.py file is just a set of regular expressions, so you have control over the URL scheme you want to use:
urlpatterns = patterns('',
url(r'^warehouse_(?P<slug>[_w]+).html$', 'warehouse.views.warehouse_detail'),
)
That said, I think you would be better sticking to the usual convention of slashes

What's the best way to map the main urls in a django project?

I've got a django project that contain some apps. The main urls.py includes the urls.py from the apps I've enabled, and all is good.
Now I want to configure the project so that when you go to http://testsite/, you'll get the same page that you get when you go to http://testsite/app/.
I can do this by duplicating the corresponding line in the apps urls.py in the projects urls.py, but this feels dirty.
Anyone know a better way?
Set up a redirect_to from the first url to the second, ie:
from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
# Example:
url(r'^$', redirect_to, {'url':'/app/'}),
url(r'^app/', include('app.urls')),
# ...
)
HTH
A redirect is the way to go, because you don't want multiple canonical URLs for the same resource (wastes Google juice). Ideally, you should do the redirect as close to the edge of your stack as possible to conserve server resources. So you can do a Django redirect_to urlconf entry, but you'd be better off with an Apache or nginx or insert-your-webserver-here redirect, so the initial request never has to hit Django at all.