Ryan can fly
Ryan can fly

Reputation: 123

Django Page not found

I want to create urls to go to links like this: examples.com/baiviet/post-example/

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

Upvotes: 1

Views: 456

Answers (2)

karthikr
karthikr

Reputation: 99620

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'^'

Upvotes: 2

alecxe
alecxe

Reputation: 473763

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

Upvotes: 2

Related Questions