[英]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 = 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'
如我所见, 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.