Django - 如何从表中的按钮删除对象

问题描述 投票:0回答:1

目标: 我想使用 Django 中的按钮从表中删除对象,但它没有按预期工作。我在下面提供了代码的相关部分。有人可以指导我添加到

urls.py
views.py
中才能完成这项工作吗?

数据库属性:

  • _id
    :对象Id
  • response
    :字符串
  • 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! ❤️

django object button
1个回答
0
投票

不需要使用序列化器,它可能只会使方式变得复杂,所以我们可以使用:

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.")
© www.soinside.com 2019 - 2024. All rights reserved.