将Django模型输出为表格

编程入门 行业动态 更新时间:2024-10-11 01:12:55
本文介绍了将Django模型输出为表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个视图定义(试图)将模型输出为表格.这是我到目前为止的内容:

I have a view definition that (attempts to) outputs a model as a table. This is what I have so far:

def output_table(request): output = My_Model() return render_to_response('outputtable.html', {'output': output})

这是outputtable.html的HTML:

Here's the HTML for outputtable.html:

<html> <table> {{ output.as_table }} </table> </html>

我做错了什么?它不起作用.现在,它正确传递了模型,因为如果我将 My_Model()更改为 My_Model.objects.all(),然后将其输出为 {{output}} 然后它显示了我在Django shell中看到的内容.

What am I doing wrong? It doesn't work. Now, it's passing the model correctly, because if I change My_Model() to My_Model.objects.all() and then output it as simply {{ output }} then it shows me what I would see in the Django shell.

推荐答案

因此,您需要执行以下操作:

So what you need to do is the following:

1)添加

导入ModelForm 到您的models.py

from django.forms import ModelForm to your models.py

2)添加

class My_Model_Form(ModelForm): class Meta: model = My_Model

3)在您的views.py中,将 output = My_Model()更改为 output = My_Model_Form()

3) in your views.py, change output = My_Model() to output = My_Model_Form()

现在您已经准备就绪.因此,诀窍是从原始模型继承您的Form.

Now you are all set. So the trick is to inherit your Form from your original model.

更多推荐

将Django模型输出为表格

本文发布于:2023-10-27 23:59:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表格   模型   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!