如何分配一个带有 id 的取消按钮以从 Django 的数据库中删除给定的 id
How to assign a cancel button with an id to delete the given id from database in Django
This is our database from which I wanna assign the id to the delete it
this is how it will on HTML page the button
所以使用的按钮是一个锚标记,我正在使用 for 循环打印数据库中的所有条目,但现在我想在用户单击取消时删除该条目,但是由于 to_id并且 from_id 可以多次使用 我想根据 id 列删除所以你能建议一种方法吗
<div class="rowtemp">
<div class="col-md-6">
<div class="card card-signin1 my-5 cardpro" id="card" style=" max-width: 1600px;
max-height: 300px;
overflow: scroll;">
<div class="card-body "id="card">
<h2 style="color: #fafafa;">Challenge Requests Sent ({{ sent.count }})</h2>
<hr class="my-2" />
{% if not sent %}
<h5><i>No sent requests!</i></h5>
{% else %} {% for s_request in sent %}
<p style="color:white">{{s_request}}</p><br>
<br /><br />
{% endfor %} {% endif %}
</div>
</div>
</div>
您可以像下面这样实现:
# views.py
from django.views.decorators.http import require_http_methods
@require_http_methods(["POST"])
def delete_challenge_request(request, cr_id):
try:
cr = ChallengeRequest.objects.get(id=cr_id)
except ChallengeRequest.DoesNotExist:
pass
else:
cr.delete()
return redirect('cr-list')
# urls.py
path('challenge-request/<int:id>/delete/', views.delete_challenge_request, name='cr-delete')
# template
{% for s_request in sent %}
<form method="POST" action="{% url 'cr-delete' s_request.pk %}">{% csrf_token %}
<input type="submit" value="DELETE">
</form>
{% endfor %}
以上实现包括删除质询请求并重定向到质询请求列表视图的视图。如果您不想动态重定向和刷新页面,您可以编写 javascript 向您的视图发送 AJAX 请求并从视图发送 return JSON 响应。
This is our database from which I wanna assign the id to the delete it
this is how it will on HTML page the button
所以使用的按钮是一个锚标记,我正在使用 for 循环打印数据库中的所有条目,但现在我想在用户单击取消时删除该条目,但是由于 to_id并且 from_id 可以多次使用 我想根据 id 列删除所以你能建议一种方法吗
<div class="rowtemp">
<div class="col-md-6">
<div class="card card-signin1 my-5 cardpro" id="card" style=" max-width: 1600px;
max-height: 300px;
overflow: scroll;">
<div class="card-body "id="card">
<h2 style="color: #fafafa;">Challenge Requests Sent ({{ sent.count }})</h2>
<hr class="my-2" />
{% if not sent %}
<h5><i>No sent requests!</i></h5>
{% else %} {% for s_request in sent %}
<p style="color:white">{{s_request}}</p><br>
<br /><br />
{% endfor %} {% endif %}
</div>
</div>
</div>
您可以像下面这样实现:
# views.py
from django.views.decorators.http import require_http_methods
@require_http_methods(["POST"])
def delete_challenge_request(request, cr_id):
try:
cr = ChallengeRequest.objects.get(id=cr_id)
except ChallengeRequest.DoesNotExist:
pass
else:
cr.delete()
return redirect('cr-list')
# urls.py
path('challenge-request/<int:id>/delete/', views.delete_challenge_request, name='cr-delete')
# template
{% for s_request in sent %}
<form method="POST" action="{% url 'cr-delete' s_request.pk %}">{% csrf_token %}
<input type="submit" value="DELETE">
</form>
{% endfor %}
以上实现包括删除质询请求并重定向到质询请求列表视图的视图。如果您不想动态重定向和刷新页面,您可以编写 javascript 向您的视图发送 AJAX 请求并从视图发送 return JSON 响应。