我想为我的应用设置主页或索引页面。我尝试在 settings.py 中添加 MAIN_PAGE,然后创建一个返回 main_page 对象的 main_page 视图,但它不起作用另外,我尝试在 urls.py 中添加一个声明,如
(r'^$', index),
其中 index 应该是根目录下 index.html 文件的名称(但它显然不起作用)
在 Django 网站中设置主页的最佳方法是什么?
谢谢!
新的首选方法是使用TemplateView
该类。如果您想从direct_to_template
.
在您的主urls.py
文件中:
from django.conf.urls import url
from django.contrib import admin
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
# the regex ^$ matches empty
url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'),
name='home'),
]
注意,我选择将任何静态页面链接放在目录内index.html
自己的目录中。static_pages/
templates/
如果要引用静态页面(不经过任何动态处理),可以direct_to_template
使用django.views.generic.simple
. 在您的 URL 配置中:
from django.views.generic.simple import direct_to_template
urlpatterns += patterns("",
(r"^$", direct_to_template, {"template": "index.html"})
)
(假设index.html
位于您的模板目录之一的根目录。)
如果有人搜索答案的更新版本..
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$', views.index, name='index')
]
在你的views.py
def index(req):
return render(req, 'myApp/index.html')
您可以使用通用direct_to_template
视图功能:
# in your urls.py ...
...
url(r'^faq/$',
'django.views.generic.simple.direct_to_template',
{ 'template': 'faq.html' }, name='faq'),
...