html - 如何在 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)
问题: 所以,它工作得很好,但问题是它只保存最后一行。我认为有一种方法可以输入整个数据。我需要在表中输入所有数据,而不仅仅是最后一行。有人能帮我吗?
更新:行是两个列表的组合,我从文件中读取它。
解决方案
这两行是以表格形式发送的。
<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>
然后在您的视图中遍历它们。
推荐阅读
- python - 子类方法会自动继承父类抽象方法的装饰器吗?
- java - 将 SqsListener 配置为长池化
- python - 用python将大文件上传到谷歌云存储的最快方法?
- javascript - 有什么方法可以调整平面列表滚动阈值/灵敏度?
- python - 重新排序ndarray的第n维
- c# - 如何将二维数组与数组顶部和侧面的字符串数组对齐
- c - const char *m = "mnopqr" 和 const char m = "mnopqr" 有什么区别,为什么后者会导致段错误
- java - 如何使用 Arrays.asList() 启动 LinkedList
- database - 如何每月一次从逻辑上交付数据库中的内容
- python - 如何修复此代码并制作我自己的 POS 标记器?(PYTHON)