【问题标题】:Django rendering the HTML tags - How to eliminate themDjango 渲染 HTML 标签 - 如何消除它们
【发布时间】:2011-06-12 03:16:19
【问题描述】:

我正在通过 djangobook 网站学习 Django,一切进展顺利,但我创建的最新项目(处理模板)显示网页中的所有 html 标签 - 我如何消除它们?

views.py:

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html',{'current_date':now})

base.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>

current_datetime.html:

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

不幸的是,它并没有按预期显示页面,而是显示了所有的 HTML 标记。

【问题讨论】:

  • 您可以尝试使用 FireBug 来查看响应标头中设置的 Content-Type。看起来它可能是 text/plain 而不是 text/html。哦,这可能只是您的问题中的一个错字,但是当您将 html 文件列为 current_date.html 时,您的视图正在调用 current_datetime.html。
  • render_to_response() 应该默认创建一个text/html 响应。
  • 所以它显示类似&lt;title&gt;The current time&lt;title&gt; 而不仅仅是The current time ?

标签: django django-templates


【解决方案1】:

在你的 urls.py 中

from mysite.views import current_datetime

urlpatterns = patterns('',
    (r'^time/$', current_datetime),
)

模板名称必须与视图 current_datetime.html 中的名称相同

这样在终端运行服务器

$ python manage.py runserver

【讨论】:

  • 我认为这不是问题所在。所有内容都正确传输,只是格式不正确。 (它仍然有 html 标签)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2011-09-17
  • 2016-10-01
  • 2013-10-29
  • 1970-01-01
  • 2010-12-15
相关资源
最近更新 更多