This is my first Django project, so please bear with me if I'm making some basic mistakes. I'm currently working on a webpage that will display a report in an HTML table. However, I feel like the process I'm using to gather the data and construct the table might be overly complicated. While it does work, I'm sure there's a more efficient way to do this. Any advice or suggestions would be greatly appreciated.
So far, my Django project consists of a single webpage with some options for the user to control the report and a button to start report generation.
When the user initiates report generation, an XMLHTTPRequest is sent to a URL that is then directed to a view via Django. This view retrieves data from an API, processes it using Python, and then uses the render_to_string function along with a template that utilizes django_tables2 to create the table. The table is then returned as a response (wrapped in an HttpResponse) to the report webpage.
The report webpage updates the table's content by setting its innerHTML to the XMLHTTPRequest responseText.
Here is a simplified version of the flow:
- User clicks "Generate Report"
- Report page sends an XMLHTTPRequest to a view
- View fetches data from the API, processes it in Python, and renders it as a string using render_to_string and django_tables2
- The view returns the HTML of the table
- The report webpage updates the table's content with the XMLHTTPRequest responseText
This process seems a bit convoluted to me, but it's the most straightforward way I've found to generate the table. The data retrieved from the API requires some restructuring before it's suitable for the report, and Python makes this easier. Hence, the view handles this restructuring.
Thank you in advance for any help or guidance.
Here's the Django template responsible for generating the table HTML:
{% load render_table from django_tables2 %}
{% render_table report_details %}
And here's the HTML code that loads the URL to retrieve the table HTML:
<div><table id=report visibility="none"></table></div>
<body>
<script>
function load_table ()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
table_element = document.getElementById ("report");
table_element.innerHTML = this.responseText;
table_element.style.visibility = "visible";
}
};
xhttp.open("GET", "http://host:8000/reports/get_report_table", true);
xhttp.send();
}