gpt4 book ai didi

Django 在 '/' url 处提供静态 index.html View

转载 作者:行者123 更新时间:2023-11-28 19:35:00 24 4
gpt4 key购买 nike

我的 index.html 在/static/文件夹中。当我尝试时,我的 Django 应用程序运行正常:

http://127.0.0.1:8000/index.html

但我想通过 url 访问 index.html:

http://127.0.0.1:8000/

我写了一个 View 并且它有效:

class IndexView(TemplateView):
template_name = 'index.html'

我还添加到 urls.py(这让我可以像 http://127.0.0.1:8000/css/style.css 一样提供静态服务):

url(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve', {
'document_root': settings.STATIC_ROOT, 'show_indexes':True
}),

但我认为有一种方法可以在没有 TemplateView 的情况下完成我想做的事情。

有什么建议吗?谢谢。我的 django 版本是:Django 1.5

编辑:

我将 index.html 放入静态的原因:我想制作 Phonegap 兼容的 django 应用程序,所以在正确编码之后,我所要做的就是 --> 从静态文件夹制作 .zip 和将其作为移动应用程序上传到 Phonegap。简单干净。

最佳答案

您可以像这样为开发提供 static/index.html:

if settings.DEBUG:
urlpatterns += url(
r'^$', 'django.contrib.staticfiles.views.serve', kwargs={
'path': 'index.html', 'document_root': settings.STATIC_ROOT}),

但对于生产,您应该配置您的 nginx(或其他前端服务器)为 / 位置提供 index.html 文件

更新

我想解释一下你应该这样做的情况。例如,您的 Django 应用程序只有管理和 API View ,但客户端与单页应用程序(Ember、Angular 等)交互。所以你的项目至少有两个子项目,一个是你的主要 django 应用程序,第二个是一个包含所有 html/js/css 东西的客户端应用程序。将客户端脚本与 django 后端分开非常方便,它允许您的前端开发人员完成他们的工作并避免 django 存在(有一天它可以移动到不同的 repo)。

因此在这种情况下,您将获得以下构建工作流:

  1. 运行客户端应用程序源观察器以重建您的脚本/样式/模板(brunch watchgrunt 作业或gulp 观察任务)<
  2. 使用 django 收集静态数据用于生产
  3. 确保您有用于开发的 urlpatterns 修复和用于生产的正确 nginx 配置

这是我的 urls.py 示例

urlpatterns += patterns(
'django.contrib.staticfiles.views',
url(r'^(?:index.html)?$', 'serve', kwargs={'path': 'index.html'}),
url(r'^(?P<path>(?:js|css|img)/.*)$', 'serve'),
)

关于Django 在 '/' url 处提供静态 index.html View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com