从数据库 Django 向表中添加删除原始按钮
Posted
技术标签:
【中文标题】从数据库 Django 向表中添加删除原始按钮【英文标题】:Add delete raw button to table from database Django 【发布时间】:2021-11-21 19:02:39 【问题描述】:我在页面上有一个表单,可以将数据添加到数据库并显示在表格中
我需要添加一个按钮,该按钮将按 id 从数据库中删除特定行
index.html
<tbody>
% for expense_item in expense_items %
<tr>
<td> expense_item.username</td>
<td> expense_item.expense_name </td>
<td> expense_item.category </td>
<td> expense_item.cost zł</td>
<td> expense_item.date_added</td>
<td>BUTTON HERE</td>
</tr>
% endfor %
</tbody>
模型.py
class ExpenseInfo(models.Model):
username = models.CharField(max_length=255, default='NoName')
expense_name = models.CharField(max_length=20)
category = models.CharField(max_length=20)
cost = models.FloatField()
budget_id = models.CharField(default='0123456789', max_length=10)
date_added = models.DateField()
user_expense = models.CharField(max_length=20)
Views.py
def add_item(request):
budget_id = request.user.last_name
name = request.POST['expense_name']
category = request.POST['category']
expense_cost = request.POST['cost']
expense_date = request.POST['expense_date']
try:
ExpenseInfo.objects.create(username=request.user, expense_name=name, category=category, cost=expense_cost,
date_added=expense_date, user_expense=budget_id)
except ValueError or TypeError:
print('No data.')
return HttpResponseRedirect('app')
【问题讨论】:
【参考方案1】:您可以在form
标签内添加一个按钮,form
标签在td
标签内,如下所示:
<tbody>
% for expense_item in expense_items %
<tr>
<td> expense_item.username</td>
<td> expense_item.expense_name </td>
<td> expense_item.category </td>
<td> expense_item.cost zł</td>
<td> expense_item.date_added</td>
<td>
<form method="POST" action=% some url%>
% csrf_token %
<button type="submit">Button Here</button>
</form>
</td>
</tr>
% endfor %
</tbody>
【讨论】:
我知道如何添加一个按钮,但我要求一个将附加到按钮的功能以上是关于从数据库 Django 向表中添加删除原始按钮的主要内容,如果未能解决你的问题,请参考以下文章