【问题标题】:Django: Display contents of txt file on the websiteDjango:在网站上显示txt文件的内容
【发布时间】:2018-08-07 13:08:28
【问题描述】:

我的views.py中有这个

def read_file(request):
    f = open('path/text.txt', 'r')
    file_contents = f.read()
    print (file_contents)
    f.close()
    return render(request, "index.html", context)

网址.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^impala/$', views.people, name='impala'),
]

我在网站上没有看到任何内容(text.txt 文件包含信息)。 我在 nohup 中没有看到任何打印输出。 没有错误

【问题讨论】:

  • 您的urls.py 中有什么内容?此外,您没有定义context。这使我假设您没有将基于函数的视图连接到路线。
  • @YannicHamann 请参阅编辑。我的模板中也有 base.html,我在 index.html 中继承

标签: python django python-2.7


【解决方案1】:

如果您的views.py 中有read_file 功能,请将您的urls.py 调整为:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^test/$', views.read_file, name='test'),
    url(r'^impala/$', views.people, name='impala'),
]

修复基于函数的视图:

from django.http import HttpResponse

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    return HttpResponse(file_content, content_type="text/plain")

启动您的开发服务器并访问localhost:port/test。你应该看到test.txt的内容。

如果您想将文本文件的内容传递给您的template.html,请将其添加到context 变量并在您的模板中使用{{ file_content }} 访问它。

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    context = {'file_content': file_content}
    return render(request, "index.html", context)

请记住,出于性能原因,nginxapache 这样的网络服务器通常会负责提供静态文件。

【讨论】:

  • 我成功使用了 localhost:port/test,我确实看到了文件中的文本。试图让它出现在主站点上
  • 主站点是什么意思?您想更改网址还是将其连接到您的模板?
  • 对不起,我的意思是把它连接到我的模板。仍然无法做到这一点,我的模板中有变量,但没有显示
  • 您可以将{% debug %}添加到您的模板中,以查看当前上下文的内容。
  • @YannicHamann 当我添加{% debug %} 时出现此错误。 {'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'ERROR': 40, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30}, 'csrf_token': ._get_val at 0x10dd11268>>,
【解决方案2】:

您可以将文件内容作为字符串传递给您的 html 模板

def read_file(request):
    f = open('path/text.txt', 'r')
    file_contents = f.read()
    f.close()
    args = {'result' : file_contents }
    return render(request, "index.html", context, args)
#######################index.html


   
<HTML>
 ...
   <BODY>
      <P>{{ result }} </p>
   </BODY>
</HTML>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2013-10-23
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多