我目前正在使用Django 1.5,无法弄清楚如何显示一个简单的html页面。我一直在阅读基于类的 View ,但是不确定这是我想要做的。

我正在尝试显示一个简单的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中放入什么内容才能实际index.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

最佳答案

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

10-07 19:50
查看更多