在另一个模板中从Django视图显示HTML表 [英] Displaying an HTML table from a Django view in another template
问题描述
因此,我有一个Django视图,该视图允许用户上传文件,并通过Pandas数据框绘制要绘制的数据.然后在单独的视图中创建图形,并通过图像标签在原始文件上传视图中引用该图形.这完美地工作.
So I have a Django view that allows for users to upload a file with data to be graphed via a Pandas dataframe. The graph is then created in a separate view which is referenced within the original file upload view via an image tag. This works perfectly.
现在,我还想以表格格式在图形图像旁边显示数据.我正在使用Panda内置的dataframe.to_html()
在单独的视图中创建表,该视图也将在文件上载视图中引用.
Now I would also like to display the data in a table format next to the image of the graph. I'm using Panda's built in dataframe.to_html()
to create the table in a separate view that will also be referenced within the file upload view.
我已正确生成该表,并且可以在为该表指定的URL上看到.尝试从文件上传模板中引用该URL时遇到错误.
I have the table generated correctly and can be seen at the URL specified for the table. I'm running into an error when I try to reference that URL from within my file upload template.
错误是:
Resource interpreted as Image but transferred with MIME type text/html
我发现这是由于我的文件上传模板包含以下行:
I discovered that this is due to the fact that my file upload template has this line:
<img src="{% url 'html_graph' %}" />
,因为视图返回的HttpResponse
的content_type
为text/html
.
since the view is returning an HttpResponse
with a content_type
of text/html
.
是否可以从我的文件上传模板中引用HTML表格视图,而该表格不使用image标签,因为该表格是HTML而不是图片?
这是我正在执行的实现:
Here is my working implementation:
html_table = df.to_html(index=False)
return render_to_response('myapp/my_template.html', {'html_table': html_table}, RequestContext(request))
然后我在模板中引用html_table
,例如:
I then reference that html_table
in my template like:
<div>
{{ html_graph | safe }}
</div>
推荐答案
要对其进行处理,您可以执行下列操作之一:
To work over it you can do one of the following listed below:
- 以这种方式使用
<pre>
标记,所有转义的字符(例如< >
等)都将按以下方式呈现:
- Use
<pre>
tag this way all the escaped characters like< >
etc will be rendered as it is can be done as:
<pre>
{{ html_table }}
</pre>
<pre>
{{ html_table }}
</pre>
- 使用django内置程序中可用的
autoescape
过滤器可以通过以下方式完成:
- Use the
autoescape
filter available in django builtins can be done as:
{% autoescape off %}
{{ html_table }}
{% endautoescape %}
{% autoescape off %}
{{ html_table }}
{% endautoescape %}
第二个选项更好,因为它是django给出的,并且只有开发者才有权使用它.
The second option is better as it is given by django and only the developer has the authority over it.
这篇关于在另一个模板中从Django视图显示HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!