簡體   English   中英

在django_tables2中使用類列表作為表類的模型

[英]Using a list of classes as a model for table class in django_tables2

我嘗試使用與Django中與我的數據庫無關的類創建表,並且該類存儲在models.py ,如下所示( InfoServer是該類)。 我想做的就是使用此類使用django_tables2填充表。 添加models.Model作為參數不是一種選擇,因為我不想將此類保存在數據庫中。

每當我在tables.py定義model = InfoServertables.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'

如我所見, InfoServer類不是Django模型。 而且我也不認為您需要直接使用它。 因此,您只需提供一個包含字典的列表,然后將其呈現在帶有表的模板中。

首先,我們將需要更新Table類並從中刪除Meta類,因為我們將不使用任何django模型。

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中找到有關如何使用數據填充表的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM