每当我尝试访问我网站上的“blog /”时,Django都会给我404错误,但我已经定义了我想要的网址,他们应该匹配。
主要urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from blog import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mySiteProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
blog.urls.py:
from django.conf.urls import patterns,url
from blog import views
urlpatterns = patterns(
url(r'^$',views.index,name='index')
)
404页面:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/blog/
Using the URLconf defined in mySiteProject.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, blog/, didn't match any of these.
网站结构:
mySiteProject
blog
admin.py
models.py
tests.py
views.py
urls.py
__init__.py
mySiteProject
wsgi.py
settings.py
urls.py
__init__.py
manage.py
db.sqlite3
已安装的应用:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
)
答案 0 :(得分:6)
patterns
需要前缀作为其第一个参数,后跟零个或多个参数。所以这个:
urlpatterns = patterns(url(r'^$',views.index,name='index')) # won't work
blog.urls.py
中的应如下所示:
urlpatterns = patterns('', url(r'^$', views.index, name='index')) # now has a prefix as first argument
在目前状态下,patterns
中的blog.urls.py
函数将返回空pattern_list
,这意味着url(r'^blog/', include('blog.urls'))
将不返回任何模式。