目标: 我想使用 Django 中的按钮从表中删除对象,但它没有按预期工作。我在下面提供了代码的相关部分。有人可以指导我添加到
urls.py
和 views.py
中才能完成这项工作吗?
数据库属性:
_id
:对象Idresponse
:字符串contact_id
:字符串status
:字符串views.py:
def delete(request, id):
try:
excel_data = get_object_or_404(ExcelData, id=id)
excel_data.delete()
return redirect('web_services_app:tables')
except ExcelData.DoesNotExist:
# Handle the case where the object doesn't exist
return HttpResponse("The object you're trying to delete doesn't exist.")
**urls.py:**
path('delete/<int:id>/', views.delete, name='delete'),
**HTML Table in tables.html:**
<div class="table-responsive">
<table class="table table-striped" id="data-table">
<thead>
<tr>
<th scope="col" style="font-weight: bold; color: black;">Response</th>
<th scope="col" style="font-weight: bold; color: black;">Contact ID</th>
<th scope="col" style="font-weight: bold; color: black;">Status</th>
<th scope="col" style="font-weight: bold; color: black;">Actions</th>
</tr>
</thead>
<tbody>
{% for data in excel_data %}
<tr class="table-row">
<td class="table-data">{{ data.response }}</td>
<td class="table-data">{{ data.contact_id }}</td>
<td class="table-data">{{ data.status }}</td>
<td>
<a class="btn btn-danger" href="/web_services_app/delete/{{ data.id }}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
I appreciate any help you can provide. Thank you! ❤️
不需要使用序列化器,它可能只会使方式变得复杂,所以我们可以使用:
def tables(request):
excel_data = ExcelData.objects.all()
return render(request, 'tables.html', {'excel_data': excel_data})
{% url … %}
模板标签[Django-doc],并使用 pk
,因为这将使用主键字段,无论其名称是什么:
<a class="btn btn-danger" href="{% url 'web_services_app:delete' data.pk %}">Delete</a>
我们在视图中做同样的事情:
def delete(request, id):
try:
excel_data = ExcelData.objects.get(pk=id)
excel_data.delete()
return redirect('web_services_app:tables')
except ExcelData.DoesNotExist:
return HttpResponse("The object you're trying to delete doesn't exist.")