Reputation: 3450
I'm having an issue with a page running on Django 2.1. My issue is that when a function is called from views.py to populate a template, an instance of a class seems to be cached. Every subsequent call to that function/every refresh of that page shows old data from the previous time that page/function was called.
The code in question:
projectroot/myapp/templates/myapp/bar.html
#this is bar.html
{{ MyTable.DataColumns }}
<br>
{{ MyTable.DataRows }}
projectroot/myapp/views.py
#this is a relevant snippet from views.py
#There isn't anything outside of the functions,
#with imports being the exception to this rule
import myownpackage.DataTable import DataTable
def list_page(request):
template = 'foo/bar.html'
connection = a_connection_here
query_results = connection.get_query_results(sql_query_here)
list_of_rows = [x for x in query_results]
dt = DataTable()
dt.DataColumns = [list_of_columns_here]
for each_row in list_of_rows:
dt.add(each_row)
return_dict = {"MyTable": dt}
return render(request, template, return_dict)
projectroot/myownpackage/DataTable.py
class DataTable:
DataColumns = []
DataRows = []
def add(self, data_row):
if len(self.DataColumns) != len(data_row):
raise IndexError("Target column count does not match DataTable's DataColumn count.")
else:
self.DataRows.append(data_row)
def remove(self, index):
self.DataRows.remove(index)
The first time this page is loaded, foo/bar.html appears to be just what I want. I can see the columns printed to the page, and the few rows in that table. The problem is visible if you refresh the page. It's as if dt is being cached after the function has returned the render().
When you refresh the page, you'll see the columns, and the rows from the first request duplicated! If we refresh a third time, we'll see a third set of those same rows! This appending of the DataTable goes on for as many times as you refresh. Clearly, dt is being stored outside of this function after being instantiated within the function, and I'm not sure why, or how, this is happening.
NOTE: Only the rows are being added over and over again. The columns remain the same. This is because the columns are being set on the table, while the rows are being added.
Things I've tried:
After dt is assigned to that return_dict, I've tried dt = None and del dt. Neither of these worked, and the same results were shown when refreshing the page.
My questions to Stack Overflow:
Why isn't the instance of DataTable called dt being thrown away after the function returns?
If this (for whatever the reason may be) is normal, what can I do to destroy that instance of DataTable when I'm done with it?
Upvotes: 0
Views: 108
Reputation: 3450
It turns out, the issue was that the DataRows were static in the DataTable class. That class should look like this:
class DataTable:
def __init__(self):
self.DataColumns = []
self.DataRows = []
Upvotes: 1