【问题标题】:Displaying simple html pages DJango显示简单的 html 页面 DJango
【发布时间】:2013-03-18 10:38:39
【问题描述】:

我目前正在使用 Django 1.5,但不知道如何显示一个简单的 html 页面。我一直在阅读有关基于类的视图,但不确定这是我想要做的。

我正在尝试显示一个简单的 index.html 页面,但根据我看到的一些示例,我需要将此代码放在 app/views.py 中:

    def index(request):
        template = loader.get_template("app/index.html")
        return HttpResponse(template.render)

为什么我的 index.html 页面必须与与我的 django 项目关联的应用程序相关联?对我来说,将 index.html 页面与整个项目对应起来似乎更有意义。

更重要的是,在我的 views.py 文件中使用此代码,我需要在我的 urls.py 中放入什么才能真正索引.html?

编辑:

Django 项目结构:

webapp/
    myapp/
        __init__.py
        models.py
        tests.py
        views.py
    manage.py
    project/
        __init__.py
        settings.py
        templates/
            index.html
        urls.py
        wsgi.py

【问题讨论】:

  • 阅读 django 教程会更有帮助。

标签: html django web


【解决方案1】:

urls.py

from django.conf.urls import patterns, url
from app_name.views import *

urlpatterns = patterns('',
    url(r'^$', IndexView.as_view()),
)

views.py

from django.views.generic import TemplateView

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

根据@Ezequiel Bertti 的回答,删除app

from django.conf.urls import patterns
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^index.html', TemplateView.as_view(template_name="index.html")),
)

您的 index.html 必须存储在模板文件夹中

webapp/
    myapp/
        __init__.py
        models.py
        tests.py
        views.py
        templates/      <---add
            index.html  <---add
    manage.py
    project/
        __init__.py
        settings.py
        templates/      <---remove
            index.html  <---remove
        urls.py
        wsgi.py

【讨论】:

  • 凯瑟琳,我在 urls.py 中遇到了“name='index'”的语法错误。你确定它不是 template_name 或不同的东西吗?谢谢!
  • 现在它只是给了我一个 templatedoesnotexist 错误。我需要的 index.html 文件有什么特别之处吗?我现在只是把它放在我的应用程序/里面,但它似乎不知道它是什么/在哪里?
  • 嗯,我实际上已经尝试过了,并且在“模板”目录中遇到了同样的问题。
  • erg 在进行所有这些更改后,我运行本地服务器并转到 localhost:8001/index.html(我选择的端口),它仍然给出了一个 templatedoesnotexisterror。顺便说一句,谢谢你的帮助,我真的很感激。
  • 请您的应用程序 urls.py 代码,它不是localhost:8001/index.html,这取决于您的 urlname
【解决方案2】:

您可以使用 django core 的 GenericView:

from django.conf.urls import patterns
from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^index.html', TemplateView.as_view(template_name="index.html")),
)

【讨论】:

  • 当我以这种方式运行时,我只是不断收到“TemplateDoesNoteExist”错误...
  • 如果您不断收到“TemplateDoesNoteExist”错误,请尝试设置项目的 settings.py 文件,更新 TEMPLATE -> DIRS 为您的文件路径,您必须指明模板文件夹的位置跨度>
【解决方案3】:

确保您已在 setting.py 中配置了路径。可能它会解决 TemplateDoesNoteExist 错误。

你可以把下面的放在settings.py中。

SETTINGS_PATH = os.path.normpath(os.path.dirname(file))

TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, '模板'), )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多