Python 2.7 + Django 1.7
我得到了:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/home/
Using the URLconf defined in home.urls, Django tried these URL patterns, in this order:
^(?P<pk>\d+)/home/$ [name='home']
^(?P<pk>\d+)/services/$ [name='services']
^(?P<pk>\d+)/contact/$ [name='contact']
The current URL, home/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
家/ urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from home import views
urlpatterns = patterns('',
url(r'^(?P<pk>\d+)/home/$', views.Home(), name='home'),
url(r'^(?P<pk>\d+)/services/$', views.Services(), name='services'),
url(r'^(?P<pk>\d+)/contact/$', views.Contact(), name='contact')
)
的mysite / urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', include('mysite.home.urls', namespace="home")),
url(r'^services/', include('home.urls', namespace="services")),
url(r'^contact/', include('home.urls', namespace="contact"))
)
这是为什么?
项目结构:
sitename
db.sqlite3
home
__init.py
admin.py
models.py
static
home.html
services.html
contact.html
urls.py
views.py
manage.py
mysite
__init.py
settings.py
urls.py
wsgi.py
这不包括一些pyc或pycache文件。 (我需要添加更多细节进行编辑,所以我想我会添加更多文字。也许这就是它想要的。我不知道。)
答案 0 :(得分:2)
家/ urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from home import views
urlpatterns = patterns('',
url(r'^home/$', views.Home(), name='home'),
url(r'^services/$', views.Services(), name='services'),
url(r'^contact/$', views.Contact(), name='contact')
)
的mysite / urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('home.urls', namespace='mysite')),
)
我不确定您是否真的想要一个pk
用于您的家庭应用,但如果您只是将您的root urlconf更改为此。
url(r'^(?P<pk>\d+)/', include('home.urls', namespace='mysite')),
您可以在此处查看urlconf文档:https://docs.djangoproject.com/en/1.7/topics/http/urls/#including-other-urlconfs
答案 1 :(得分:1)
扩展@Ngenator的注释,你的主urls.py文件中的url模式将所有内容路由到url结构,前面是:
并且阅读/猜测你想要做什么,你可能不需要:
(?P<pk>\d+)
当你想在views.py文件中获取参数pk时,你会使用它,如:
def my_view(request, pk):
因此,我的猜测是你可以在一个mysite / urls.py文件夹中定义你的url模式。
在我看来,在home / urls.py文件中定义服务和联系是没有意义的。如果你真的有家庭,联系人,管理员等应用程序,你可能只需要所有其他名称空间。
这有意义吗?您不需要为每个应用程序定义urls.py。如果您想保留home / urls.py的urls.py结构,同时保持像http://localhost.com:8000/home/这样的网址结构,那么在您的home / urls.py中,您可以执行以下操作:
url(r'^', home.views.Home(), name='home'),
假设您的home / views.py文件具有如下函数:
def Home(request):