django url regular expressions capture invalid url - regex

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

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 changes but doesn't render the proper view

I have a url setup with the following view (the url is in the app and the app urls are included in the project):
url(r'^details/(?P<outage_id>\d+)/$', 'outage.views.outage_details'),
def outage_details(request, outage_id=1):
outage_info = Outages.objects.filter(id=outage_id)
return render_to_response('templates/outage/details.html', {'outage_info': outage_info}, context_instance=RequestContext(request))
When I click on the link from http://localhost:8000 the url in the browser changes to http://localhost:8000/outage/details/1 as it should, but the view doesn't render the right template. The page stays the same. I don't get any errors, the url changes in the browser but the details.html template doesn't render. There is an outage in the DB with an ID of 1.
Any thoughts?
The regular expression r'^details/(?P<outage_id>\d+)/$' does not match the URL http://localhost:8000/outage/details/1. However, it should match the expression r'^outage/details/(?P<outage_id>\d+)/$'.
Perhaps, you can post your entire urls.py to find out which view is actually being called, since you don't get any errors. I suspect your home page is being called for all URLs.
Here is my url setup:
project/urls.py
urlpatterns = patterns('',
url(r'^$', 'outage.views.show_outages'),
url(r'^inventory/', include('inventory.urls')),
url(r'^outage/', include('outage.urls')),
url(r'^login', 'django.contrib.auth.views.login', {'template_name': 'templates/auth/login.html'}),
url(r'^logout', 'django.contrib.auth.views.logout', {'next_page': '/'}),
url(r'^admin/', include(admin.site.urls)),
)
outage/urls.py
urlpatterns = patterns('',
url(r'^', 'outage.views.show_outages'),
url(r'^notes/(?P<outage_id>\d+)/$', 'outage.views.outage_notes', name='notes'),
)
I have since changed the details to notes, since I had another page in a different app with a details url and I didn't want it somehow confusing things.

Having trouble separating urls.py

Hello I'm a newbie in Django.
I'm creating a blog app for practice and I wanted to separate the urls that relates to the blog application from the urls that relates to the other applications.
Since there are many blog-related url patterns, I just included in the main urls.py.
Here is my urls.py:
My_Project/My_Project/urls.py
urlpatterns = patterns('',
# Blog
url(r'^$', include('app_blog.urls'), name='app_blog'),
# Admin
url(r'^admin/$', include(admin.site.urls), name='admin_page'),
......
My_Project/app_blog/urls.py
urlpatterns = patterns('',
# Index page
url(r'^index/$', index_page),
# User page
url(r'^user/(?P<pk>\d+)/', UserDetail.as_view(), name='user_detail'),
......
So I expected that when I navigate to "www.example.com/index" the browser would show the index_page view and for "www.example.com/user/1", it will show the user detail view for user with id equal to 1.
For some reason, however, it shows the 404 page not found error for both pages.
Where have I gone wrong?
name parameter is for a single url pattern. Remove it from this line in My_Project/My_Project/urls.py
The regex pattern should not be '^$'. Instead just plain ''.
url(r'', include('app_blog.urls'))
The problem is here:
# Blog
url(r'^$', include('app_blog.urls'), name='app_blog'),
~~~
You are restricting your url to an empty path, that means everything that is not an empty path will not be matched against app_blog.urls.
Do this instead:
# Blog
url(r'^', include('app_blog.urls')),

Redirection in Django URLs

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.