Django/Python - 使用表单按钮删除 sqlite3 数据库中的行
我想要一个删除按钮来删除 sqlite3 数据库中的一行。我已经快到了,但我不确定应该添加什么来将行的 html
中的 ID 发送到我的 views.py
。这就是我所拥有的:
mailindex.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a>
<button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button>
</div>
</form>
views.py
class MailboxView(generic.ListView):
extra_context = {"mailbox_page": "active"}
model = MailMessage
context_object_name = 'mails'
template_name = 'core/mailbox/mailindex.html'
def post(self, request):
# if 'deletemail' in self.request.POST:
if request.POST.get('deletemail'):
mail = MailMessage.objects.get(pk=13)
mail.delete()
return HttpResponseRedirect(self.request.path_info)
它有效,从某种意义上说,当我按下删除按钮时,它会删除 ID = 13 的电子邮件。这是合乎逻辑的正如我所说的那样。那里有 13 个。我想用 mail.id 替换“13”,但我不知道该怎么做。我希望这是可能的:我希望它尽可能简单,这样就不会创建额外的网址,但同样不知道这是否可能......
I want to have a delete button to delete a row in my sqlite3 database. I'm almost there but I'm not sure what I should add to send the ID from my html
of the row to my views.py
. This is what I have:
mailindex.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a>
<button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button>
</div>
</form>
views.py
class MailboxView(generic.ListView):
extra_context = {"mailbox_page": "active"}
model = MailMessage
context_object_name = 'mails'
template_name = 'core/mailbox/mailindex.html'
def post(self, request):
# if 'deletemail' in self.request.POST:
if request.POST.get('deletemail'):
mail = MailMessage.objects.get(pk=13)
mail.delete()
return HttpResponseRedirect(self.request.path_info)
It works, in a sense that when I push the delete button it deletes email with ID = 13. Which is logical as I put no. 13 there. I would like to replace '13' with the mail.id, but I'm not sure how to do this. I hope it is possible: I would prefer it to be as simple as possible, so to not create an extra url, but again don't know if this is possible...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在类型中使用deletemail标签:隐藏另一个输入而不是按钮。
Use deletemail tag in type:hidden another input not button.
试试这个
Try this