![](/img/trans.png)
[英]Data from POST request not passed from template/form to view in django
[英]Add data from request POST into a table template [Django, Python]
我從 SQLite 數據庫創建了一個表顯示書籍信息,我正在嘗試創建一個“添加新書表單”以使其將新書添加到表數據庫中。 我怎樣才能添加一本書,然后讓它顯示在表 Book Info 中?
<div class="container-fluid">
<!-- Add Book -->
<div class="add-book">
<h1>Add a Book</h1>
<form action="/add_book" method="POST" class="add_more_book">
{% csrf_token %}
<p>
<label for="title" id="title">Title:</label>
<input type="text" name="title" class="form-control" id="input-title" />
</p>
<p>
<label id="desc" for="desc">Description:</label>
<textarea class="form-control" name="description" id="input-desc" rows="3"></textarea>
</p>
<button type="submit" class="btn shadow btn-primary" id="addbtn">
Add
</button>
</form>
</div>
<!-- End of Add Book -->
<!-- Book info -->
<div class="book-info">
<form action="/" method="POST">
{% csrf_token %}
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for i in all_books_info %}
<tr>
<th scope="row">{{i.id}}</th>
<td>{{i.title}}</td>
<td><a href="/books/{{i.id}}">Views</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</div>
假設您的 models.py 文件中有一個名為 Bio 的表。 像這樣
class Bio(models.Model):
author = models.CharField(max_length= 20, null=True)
book = models.CharField(max_length= 20, null=True)
title = models.CharField(max_length=50)
desc = models.CharField(max_length=200)
假設您已經在 views.py 文件的頂部導入了模型。
from .models import *
* 從模型文件中導入所有模型。(您將來可能會或可能不想導入所有模型。)
在views.py 文件中
def processInfo(request):
print(request.POST["title"]
if len(str(request.POST["title"])) < 2:
print("Needs more the 2 characters to submit")
else:
print("Meets rule")
Bio.objects.create(title = request.POST["title"])
打印件在那里查看是否收到任何東西。 你總是想先檢查你是否沒有得到一個空字符串。 我使用 len 和其他工具檢查https://www.w3schools.com/python/ref_func_len.asp有幾種方法可以從 django 模型中創建和獲取數據。 https://docs.djangoproject.com/en/3.0/topics/db/queries/
最后對於在views.py文件中呈現“/”的function。 檢索到要查找的數據后,將其與請求和 html 文件一起返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.