如何在Django中返回静态HTML文件作为响应?

时间:2013-01-18 13:32:46

标签: python django static-html

我还没弄清楚如何使用纯HTML代码和/或HTML + JavaScript + CSS来展示网站。

我尝试加载一个HTML文件,上面只写着: Hello World

我知道我也可以用Django做到这一点,但后来我想用CSS + JavaScript + HTML显示我的网站。

在视图文件中,我运行以下代码:

# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader

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

但网站显示的唯一内容是:

  

>

6 个答案:

答案 0 :(得分:16)

您没有在那里调用render方法,是吗?

比较

template.render

template.render()

答案 1 :(得分:15)

如果你的文件不是django模板而是普通的html文件,这是最简单的方法:

from django.shortcuts import render_to_response

def index (request):
    return render_to_response('app/index.html')

答案 2 :(得分:9)

如果您的CSS和JS文件是静态的,请不要使用Django来提供它们,或者serve them as static files

对于你的html,你可以做同样的事情,如果它只是一些没有任何动态内容的固定文件。您也可以将generic viewsTemplateView一起使用,只需在urls.py中添加这样的一行:

    url(r'^path/to/url', TemplateView.as_view(template_name='index.html')),

答案 3 :(得分:8)

使用HttpResponse您只能发送数据,如果您想要html文件,那么您必须通过以下方式使用renderrender_to_response ...

from django.shortcuts import render

def index(request):    
    return render(request, 'app/index.html')

from django.shortcuts import render_to_response

def index (request):
    return render_to_response('app/index.html')

答案 4 :(得分:0)

from django.http import HttpResponse

from django.template import loader

def index(request):

    template=loader.get_template('app/index.html')

    return HttpResponse(template)

答案 5 :(得分:0)

首先,您需要进行一些模板设置:

在创建项目后,在 root 目录中的

Create“ templates”文件夹中,manage.py位于该文件夹中。 然后转到 settings.py ,在“模板”部分中输入“ templates”文件夹的目录。不建议使用硬编码,因为如果将项目发送给您的朋友,您的朋友将无法运行它。应该是这样的:

TEMPLATES = [
 {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

假设您在模板文件夹中有 home.html about.html

urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('about/',views.aboutview),
    path('',views.homeview),
]

views.py

from django.http import HttpResponse
from django.shortcuts import render

def aboutview(request):
  return render(request,"home.html")
def homeview(request):
  return render(request,"about.html")