我想为我的应用程序设置主页或索引页。我尝试在settings.py中添加MAIN_PAGE,然后创建一个返回main_page对象的main_page视图,但同样不起作用,我尝试在urls.py中添加如下声明
(r'^$', index),
其中it应该是根目录上的index.html文件的名称(但它显然不起作用)
在Django网站中设置主页的最佳方式是什么?
谢谢!
发布于 2010-07-08 21:34:38
如果您想引用一个静态页面(不对其进行任何动态处理),可以使用django.views.generic.simple
中的direct_to_template
视图函数。在URL配置文件中:
from django.views.generic.simple import direct_to_template
urlpatterns += patterns("",
(r"^$", direct_to_template, {"template": "index.html"})
)
(假设index.html
位于某个模板目录的根目录中。)
发布于 2016-03-21 20:05:06
新的首选方法是使用TemplateView
类。如果您想从direct_to_template
迁移,请参阅此SO answer。
在主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
的静态页面放在templates/
目录下它自己的目录static_pages/
中。
发布于 2019-03-21 14:40:29
以防有人搜索更新版本的答案..
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')
https://stackoverflow.com/questions/3204060
复制相似问题