首页 > 解决方案 > 如何在 Django 2.1 中将表存储到数据库中?

问题描述

我在 html 中有一个表,我需要使用视图、模型和表单将其保存到数据库中。以下是部分代码:

模板.html

<form method="post" action="/images/save/" enctype="multipart/form-data">
    {% csrf_token %}
    <table class="table" border="1" id="tbl_posts">
    <tbody id="tbl_posts_body">

    {% for name, age in lines %}
    {% with i=forloop.counter0 %}
    {% with i|add:1|stringformat:"s" as i_id %}
    {% with id="rec-"|add:i_id %}

    <tr id={{id}}>
        <td><span class="sn">{{ i|add:1 }}</span>.</td>
        <td><INPUT type="text" name="txt1" value=""\></td>
        <td><INPUT type="text" name="txt2" value=""\></td>
    </tr>

    {% endwith %}
    {% endwith %}
    {% endwith %}
    {% endfor %}

    </tbody>
    </table>
    <input type="submit" value="Submit">
 </form>

模型.py:

class Names(models.Model):
    name= models.CharField(max_length=255)
    age= models.IntegerField()

视图.py:

def save_form(request):
    template = "template.html"
    context = {'txt1': "Name", 'txt2': 0}
    if request.method == 'POST':
        dname= request.POST.get("txt1")
        dage= request.POST.get("txt2")
        names1= Names(name=dname, age=dage)
        names1.save()

    return render(request, template, context)

问题: 所以,它工作得很好,但问题是它只保存最后一行。我认为有一种方法可以输入整个数据。我需要在表中输入所有数据,而不仅仅是最后一行。有人能帮我吗?

更新:行是两个列表的组合,我从文件中读取它。

标签: htmldjango

解决方案


这两行是以表格形式发送的。

<td><INPUT type="text" name="txt1" value=""\></td>
<td><INPUT type="text" name="txt2" value=""\></td>

但是,您使用相同的“名称”来发送多行的值。结果是,您只能使用视图中的当前代码获取这些值一次。你会想给他们每个人一个唯一的名字(只要做这样的事情:

<td><INPUT type="text" name="txt{{forloop.counter}}" value=""\></td>

然后在您的视图中遍历它们。


推荐阅读