在django中删除带有表单的对象

Seb*_*ian 5 django

我正在显示一个表格。在每一行中都应该有一个删除按钮,用于从表中删除元素。

\n\n

我的问题是,我不确定如何将元素的 id 传递给视图。

\n\n

html:

\n\n
{% for post in posts %}\n    <div>\n        <h3>Zuletzt ausgew\xc3\xa4hlt:</h3>\n        <p>published: <b>{{ post.pub_date }}</b>\n        </p>\n        <p>\n            name: <b>{{ post.Name }}</b>\n            anmeldung: <b>{{ post.get_Anmeldung_display }}</b>\n            essen: <b>{{ post.get_Essen_display }}</b>\n                <form action="" method="POST">\n                  {% csrf_token %}\n                  <input class="btn btn-default btn-danger" name="delete" type="submit" value="L\xc3\xb6schen"/>\n                </form>\n        </p>\n        <p>\n            Email: <b>{{ post.Email }}</b>\n        </p>\n    </div>\n{% endfor %}\n
Run Code Online (Sandbox Code Playgroud)\n\n

视图.py

\n\n
if request.method == \'POST\' and \'delete\' in request.POST:\n    Eintrag.objects.filter(pk=id).delete()\n    return HttpResponseRedirect(request.path)  \n
Run Code Online (Sandbox Code Playgroud)\n\n

所以我需要将每个帖子的 post.pub_date 传递给视图,我怎样才能做到这一点?

\n

xyr*_*res 4

我的问题是,我不确定如何将元素的 id 传递给视图。

我可以想到两种方法来做到这一点。我将一一介绍它们。

1.在您的应用程序中创建一个单独的 url 路由,专门用于删除对象:

('/post/<pk>/delete/', name="delete_post"),
Run Code Online (Sandbox Code Playgroud)

然后将您的表单action指向此网址:

<form action="{% url 'delete_post' post.pk %}" method="POST">
    ...
Run Code Online (Sandbox Code Playgroud)

最后,修改视图函数以接受pk参数:

def my_view(request, pk): 
    ...
Run Code Online (Sandbox Code Playgroud)

2.第二种方法是在表单中创建另一个字段并向其传递对象的 pk:

只需在表单中创建另一个字段即可。

<form action="" method="POST">
    <input type="hidden" value="{{ post.pk }}" name="pk">
    ...
Run Code Online (Sandbox Code Playgroud)

然后在你看来只要看看request.POST['pk']就可以得到帖子的pk。