我想为我的应用程序设置主页面或索引页面。我尝试在settings.py中添加MAIN_PAGE然后创建一个main_page视图返回一个main_page对象,但它不起作用另外,我试图在urls.py中添加一个声明,如
(r'^$', index),
其中index应该是根目录下index.html文件的名称(但显然不起作用)
在Django网站中设置主页的最佳方法是什么?
谢谢!
如果你想引用一个静态页面(没有经过任何动态处理),你可以使用direct_to_template
中的django.views.generic.simple
视图函数。在您的网址中:
from django.views.generic.simple import direct_to_template
urlpatterns += patterns("",
(r"^$", direct_to_template, {"template": "index.html"})
)
(假设index.html
位于您的某个模板目录的根目录。)
这样做的新首选方法是使用TemplateView
类。如果你想从SO answer搬家,请看这个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
目录中的qazxsw poi自己的目录中。
您可以使用通用的static_pages/
视图功能:
templates/
如果有人搜索答案的更新版本..
direct_to_template
在你的# in your urls.py ...
...
url(r'^faq/$',
'django.views.generic.simple.direct_to_template',
{ 'template': 'faq.html' }, name='faq'),
...
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$', views.index, name='index')
]