未找到参数为“(“”,)”的“customerdel”的反转。尝试了1种模式:[“dashboard/records/customerdel/(?P<pk>[09]+)$”]

2024-09-27 00:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用简单的html按钮从数据库中删除一个对象。另外,尝试实现“您确定”消息?但我每次都会犯这个错误,我无法破解

这是我的视图函数

    def customerdel(request,pk):
        objs = Customer.objects.filter(id=pk)
        if request.method == 'POST':
            objs.delete()
            # messages.success(request, 'Successfully deleted')
            return render(request,'records.html')

        else:
            content ={
             'items':Customer.objects.all
            }
            return render(request,'delete.html', content)

这是record.html页面

<h1>Record's page</h1>

{% for abc in Customerdata %}
{{abc.name}}
{{abc.pk}}


<form >
    <button  class="btn btn-danger btn-sm">
    <a href="{% url 'customerdel' abc.pk %}">Delete</a></button>
</form>
{% endfor %}

这是delete.html页面

<h1>Welcome to Delete page</h1>


<p>Are you sure want to del {{items.name}} ??</p>
<form action="{% url 'customerdel' items.pk %}" method="post">
    {% csrf_token %}
    <a href="{% url 'records' %}">Cancel</a>
    <input name="confirm" type="submit" >

</form>

这是我的网址

path('dashboard/records/customerdel/<int:pk>', views.customerdel, name='customerdel'),

Tags: nameformurlrequesthtmlitemscustomerdelete
1条回答
网友
1楼 · 发布于 2024-09-27 00:15:50

模板呈现时出错,因为您没有向模板发送任何数据。但是在record.html中,您试图迭代未定义的CustomerData。因此,将其发送到模板或另一种方法是直接重定向到为呈现record.html而创建的路由

以下是您应该在django项目中应用的完整代码,以使其正常工作

from django.http import HttpresponseRedirect
from django.urls import reverse #these two lines are required for redirecting to a previous route(url)

因为您必须设置一个url,该url用于记录函数,如下所示

path('records', views.records, name='records')

如果尚未添加名称,请添加它

然后在views.py中,在customerdel函数中

if request.method == 'POST':
#write your code which you already wrote and instead of return render(...) write this;
return HttpResponseRedirect(reverse('records')) #where records is the name of the url which takes us to the records page.

相关问题 更多 >

    热门问题