文件数据未在html页面中显示

时间:2015-10-16 07:09:37

标签: django

我的任务是在html页面中显示文件夹数据。但它显示空白页面请任何人帮助我,我在做错误。

view.py

def info(request,id):
    INFO_DIR = '/home/des-0064/Logs'
    req_path = os.path.join(INFO_DIR, id)
    file_content = dict()
    for root, dirs, files in os.walk(req_path):
        for file_name in files:
            full_path =  os.path.join(root,file_name)
            with open(full_path, 'r') as _file:
                #file_content[file_name] = _file.read()
                file_content[file_name] = _file.read()
    print file_content

    for file_name, content in file_content.iteritems():
        print file_name
        print content

    return HttpResponse (request, 'info.html')

2 个答案:

答案 0 :(得分:0)

您的代码只是打印到控制台,您需要在上下文变量中将其传递给您的模板。

至少你可以在创建json之后传递内容。

return HttpResponse(request,
                    'info.html',
                    {'file_contents': json.dumps(file_content.iteritems())})

然后,您可以使用模板中的file_contents

我假设您实际上可以看到控制台上打印的内容,而且所有代码都可以使用

答案 1 :(得分:0)

您需要将file_content传递给html模板。

return HttpResponse(request, 'info.html', file_contents)

如上所述传递它将允许您遍历所有文件并显示其内容。你的模板代码就是这样的。

{% for file, content in file_contents %}
    Name: {{ file }}
    Content: {{ content }}
{% endfor %}