Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an HTML table from a Django view in another template

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.

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.

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.

The error is:

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' %}" />

since the view is returning an HttpResponse with a content_type of text/html.

Is there a way to reference that HTML table view from within my file upload template that doesn't use the image tag since the table is HTML rather than an image?

Solution

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))

I then reference that html_table in my template like:

<div>
 {{ html_graph | safe }}
</div>

Edit

A correction in the template code:

<div>
 {{ html_table | safe }}
</div>
like image 989
alacy Avatar asked Dec 16 '14 19:12

alacy


People also ask

How do I join a Django template?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


1 Answers

To work over it you can do one of the following listed below:

  1. Use <pre> tag this way all the escaped characters like &lt; &gt; etc will be rendered as it is can be done as:

<pre> {{ html_table }} </pre>

  1. Use the autoescape filter available in django builtins can be done as:

{% autoescape off %} {{ html_table }} {% endautoescape %}

The second option is better as it is given by django and only the developer has the authority over it.

like image 181
RajkumarG Avatar answered Oct 22 '22 20:10

RajkumarG