在Django中删除带有表单的对象 [英] Delete object with form in django
问题描述
我正在显示一张桌子。在每一行中都应该有一个删除按钮,用于从表中删除该元素。
I'm displaying a table. In every line there should be a delete button which deletes the element from the table.
我的问题是,我不确定如何将元素的ID传递给
My problem is, I'm not sure how to pass the id of the element to the view.
html:
{% for post in posts %}
<div>
<h3>Zuletzt ausgewählt:</h3>
<p>published: <b>{{ post.pub_date }}</b>
</p>
<p>
name: <b>{{ post.Name }}</b>
anmeldung: <b>{{ post.get_Anmeldung_display }}</b>
essen: <b>{{ post.get_Essen_display }}</b>
<form action="" method="POST">
{% csrf_token %}
<input class="btn btn-default btn-danger" name="delete" type="submit" value="Löschen"/>
</form>
</p>
<p>
Email: <b>{{ post.Email }}</b>
</p>
</div>
{% endfor %}
views.py
if request.method == 'POST' and 'delete' in request.POST:
Eintrag.objects.filter(pk=id).delete()
return HttpResponseRedirect(request.path)
所以我需要传递post.pub_date
So I need to pass post.pub_date of every post to the view, how can I accomplish that?
推荐答案
我的问题是,我我不确定如何将元素的ID传递给视图。
My problem is, I'm not sure how to pass the id of the element to the view.
我可以想到两种方法。我将一一介绍它们。
I can think of two ways to do this. I'll cover them both one by one.
1。。在您的应用中创建一个单独的url路由,专门用于删除对象:
1. Create a separate url route in your app specifically for deleting objects:
('/post/<pk>/delete/', name="delete_post"),
然后将表单的操作
指向此URL:
Then point your form's action
to this url:
<form action="{% url 'delete_post' post.pk %}" method="POST">
...
最后,修改您的视图函数以接受 pk
参数:
Finally, modify your view function to accept the pk
argument:
def my_view(request, pk):
...
2。第二方法是在表单中创建另一个字段,并将其传递给对象的pk:
2. Second method is to just create another field in your form and pass it the pk of the object:
只需在表单中创建另一个字段。
Just create another field in your form.
<form action="" method="POST">
<input type="hidden" value="{{ post.pk }}" name="pk">
...
然后在您看来,仅查看请求.POST ['pk']
获取帖子的pk。
Then in your view just look at request.POST['pk']
to get the pk of the post.
这篇关于在Django中删除带有表单的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!