首页 > 解决方案 > 页面刷新后Python Django变量数据重复

问题描述

我将一个字符串传递给模板,它工作正常,但是当我重新加载页面时,该字符串被复制。

该字符串是动态生成的并包含 html-table,我想从我的模板中的变量呈现一个表

只有服务器重置有助于查看没有重复的实际表

来自views.py的代码:

def test(request):

   headings = ('RED', 'GREEN', 'BLUE')

   tb = Table()
   tb.make_headings(headings)

   cell_1 = Cell('1')
   cell_2 = Cell('2')
   cell_3 = Cell('3')

   row_1 = Row()
   row_1.add_cell(cell_1)
   row_1.add_cell(cell_2)
   row_1.add_cell(cell_3)

   tb.add_row(row_1) 

   html_table = tb.create_html_table()

   return render(request, 'test.html', context = {
       'table' : html_table
       })

create_html_table() 函数:

    def create_html_table(self):
        html_table = '<table>'
        
        for row in self.raw_table:
            html_row = '<tr>'
            for cell in row.cells:
                html_cell = '<td>{}</td>'.format(cell.get_data())
                html_row += html_cell
            html_row += '</tr>'
            
            html_table += html_row
        
        html_table += '</table>'
        return html_table

行代码:

from .cell import Cell

class Row():
    cells = []

    def __init__(self):
        self.cells = []

    def add_cell(self, cell: Cell):
        self.cells.append(cell)
        
    def get_cells(self):
        return self.cells

单元格代码:

class Cell():
    def __init__(self, data = []):
        self.data = data

    def get_data(self):
        return self.data

标签: pythondjango

解决方案


推荐阅读