Django - 直接从 urls.py 渲染 HTML 模板

Bre*_*ett 4 python django

我有一个Django应用程序(我相当新,所以我正在尽力了解细节),我希望将 url 端点重定向到另一个文件夹(应用程序)中的静态 html 文件。

我的项目文件层次结构如下所示:

docs/
 - html/
    - index.html
myapp/
 - urls.py
Run Code Online (Sandbox Code Playgroud)

我的urls.py样子:

from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^docs/$', RedirectView.as_view(url='/docs/html/index.html')),
)
Run Code Online (Sandbox Code Playgroud)

但是,当我导航到 时,http://localhost:8000/docs我看到浏览器重定向到http://localhost:8000/docs/html/index.html,但该页面无法访问。

是否有任何原因导致应用程序在这样的重定向中/docs/html/index.html无法使用?myApp

如果有人指点,我们将不胜感激。

Ren*_*Ivo 5

注意:direct_to_template自 Django 1.5 起已被弃用。使用 TemplateView.as_view代替。

我认为你想要的是Template View,而不是 RedirectView 。你可以用类似的方法来做到这一点:

urls.py

from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    (r'^docs/$', direct_to_template, {
        'template': 'index.html'
    }),
)
Run Code Online (Sandbox Code Playgroud)

只需确保路径index.html位于 TEMPLATE_DIRS 设置中,或者将其放在templates应用程序的文件夹中(此答案可能会有所帮助)。