在django_tables2中使用类列表作为表类的模型

时间:2019-05-24 10:07:21

标签: python django django-tables2

我尝试使用与Django中与我的数据库无关的类创建表,并且该类存储在models.py中,如下所示(InfoServer是该类)。我想做的就是使用此类使用django_tables2填充表。添加models.Model作为参数不是一种选择,因为我不想将此类保存在数据库中。

每当我在model = InfoServer中定义tables.py时,都会出现此错误,并且我想这是因为InfoServer没有使用models.Model作为参数。

  

TypeError:“对象”对象的描述符“ repr ”需要一个参数

感谢您的帮助。

models.py

class TestServeur(models.Model):
    nom = models.CharField(max_length=200)
    pid = models.CharField(max_length=200)
    memoire = models.IntegerField(null=True)

class InfoServer:
    # "This is a class to test my knowledge of python"
    def __init__(self,p = '',c = 0,m = 0):
        self.pid = p
        self.cpu = c
        self.memoire = m

    def getData(self):
        return ("A server with %s memory and %s cpu" % (self.cpu,self.memoire))

views.py

def index(request):
    return HttpResponse("Hello, world. You're at the index.")

def cpu_view(request):
    liste = []
    proc1 = Popen(['ps','-eo','pid,%cpu,%mem,comm'], stdout=PIPE, stderr=PIPE)
    proc2 = Popen(['grep','java'], stdin=proc1.stdout, stdout=PIPE)
    proc1.stdout.close()

    for line in iter(proc2.stdout.readlines()):
        clean_line = line.decode("utf-8")
        info_utiles = clean_line.split()
        pid,cpu,mem,*rest = info_utiles
        i1 = InfoServer(pid,cpu,mem)
        liste.append(i1)

    table = TestServeur(liste)
    RequestConfig(request).configure(table)
    return render(request, 'server/cpu.html', {'output': table})

tables.py

class TableServeur(tables.Table):
    class Meta:
        # model = InfoServer
        fields = ['pid', 'memory', 'cpu']
        template_name = 'django_tables2/bootstrap4.html'

1 个答案:

答案 0 :(得分:3)

如我所见,InfoServer类不是Django模型。而且我也不认为您需要直接使用它。因此,您只需提供一个包含字典的列表,然后将其呈现在带有表的模板中即可。

首先,由于我们将不使用任何django模型,因此我们需要更新Table类并从其中删除Meta类。

class TableServeur(tables.Table):
    pid = tables.Column()
    memory = tables.Column()
    cpu = tables.Column()

现在,添加一个新的对象方法以从InfoServer类返回字典:

class InfoServer:
    # "This is a class to test my knowledge of python"
    def __init__(self,p = '',c = 0,m = 0):
        self.pid = p
        self.cpu = c
        self.memoire = m

    def getData(self):
        return ("A server with %s memory and %s cpu" % (self.cpu,self.memoire))

    def get_dict_data(self):
        return {'pid': self.pid, 'cpu': self.cpu, 'memory': self.memoire}

最后,更新视图:

for line in iter(proc2.stdout.readlines()):
    clean_line = line.decode("utf-8")
    info_utiles = clean_line.split()
    pid,cpu,mem,*rest = info_utiles
    i1 = InfoServer(pid,cpu,mem)
    liste.append(i1.get_dict_data())
table = TestServeur(liste)
return render(request, 'server/cpu.html', {'output': table})

可以在documentation中找到有关如何使用数据填充表格的更多信息。