当我调出127.0.0.1:8000时,显示的当前页面为something.html
模板。
我需要在首次启动时使其显示为index.html,然后当我点击其他部分时,它应该转到127.0.0.1:8000/something.html(或127.0.0.1:8000/myapp/something。 HTML)。
实现这一目标的结构是什么?
我经常收到错误消息:The current URL didn't match any of these.
目前,我的结构是
project
---myapp
---admin.py
---models.py
---url.py
---views.py
---static
---templates
---myapp
---html files
---mysite
---settings.py
--- url.py
在我的settings.py
下STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
mysettings / url.py
urlpatterns = [
# Examples:
url(r'^$', 'mysite.views.home', name='home'),
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
的mysite / urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
from django.views.generic import TemplateView
urlpatterns = [
# Examples:
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
admin.site.site_header = 'Admin'
的myapp / url.py
from . import views
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
#brings up something.html when we comment it out. No module found if included.
#url(r'^$', views.home, name='home'),
url(r'^$', views.post_list, name='post_list'),
)
答案 0 :(得分:1)
myapp
mysite/urls.py
应用的网址
醇>
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
现在,从127.0.0.1:8000
开始的所有网址都会检查是否有可以处理请求的视图。我建议您阅读本文以了解Django URL调度程序的工作原理:[Django文档 - URL调度程序](https://docs.djangoproject.com/en/1.8/topics/http/urls/)。
2.在myapp.urls
中添加新路线:
from django.conf.urls import url, patterns
from . import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^something$', views.something, name='something'),
url(r'^posts$', views.post_list, name='post_list'),
)
现在:
127.0.0.1:8000/
将执行views.home
的代码
127.0.0.1:8000/something
将执行views.something
的代码
127.0.0.1:8000/posts
将执行views.post_list
的代码
我们现在定义这些视图
3:在myapp.views
中定义视图:
from django.shortcuts import render
def home(request):
"""
Return home page
"""
return render(request, 'myapp/home.html')
def something(request):
"""
Return something page
"""
return render(request, 'myapp/something.html')
def post_list(request):
"""
Return something page
"""
# do what you want
myapp/templates/myapp/
中添加模板。添加home.html
和something.html
。现在忘了,`.html
答案 1 :(得分:0)
url
(附加了view
)。view
中,您可以呈现所需的任何html页面。如果您使用基于功能的视图,则'mysite.views.home'
可能如下所示:
def home(request):
...
return render(request, 'path/to/index.html')
等等。
这是基础,所以我不会谈论这么多。您可以找到关于将网址映射到视图there的好教程。