Django:Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s)tried:['$']

brccelvz  于 2023-03-31  发布在  Go
关注(0)|答案(2)|浏览(159)

我是Django的新面孔,所以如果我的问题是愚蠢的,请考虑一下。在这种情况下,我想删除数据库中的一个项目,如果我点击按钮,html将传递一个id给views.py,然后函数Delete()将删除这个项目。但是无论我尝试什么,它都没有任何响应。
现在我在home.html中添加action="{% url 'todolist:delete' todo.id %}",但它遇到了一些错误:NoReverseMatch: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['$'],我不知道怎么解,请给予我一些建议,我会很感激的。
我的代码如下:
项目/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('todolist.urls', namespace='todolist')),
]

todolist/urls.py:

app_name = "todolist"
urlpatterns = [
    path('', views.Add, name = 'add'),
    path('', views.Delete, name = 'delete'),
]

home.html:

<form action="{% url 'todolist:delete' todo.id %}" method="post">
{% csrf_token %}
<table>
  <tbody>
    {% for each in todo_list %}
    <tr>
        <td><div class="thing"><input type="checkbox" name="done" value="done"><label>{{each.todo}}</label></div></td>
        <td><input type="button" class="edit" name="edit" value="E"></td>
        <td><input type="button" class="delete" name="delete" value="x"></td>
    </tr>
    {% endfor %}
  </tbody>
</table>
</form>

views.py:

def Delete(request, id):
    if 'delete' in request.POST:
        todo = Todo.objects.get(id=id)
        todo.delete()
        todo_list = Todo.objects.all()
        return render(request, 'todolist/home.html', {'todo_list': todo_list, 'todo': todo})
j8yoct9x

j8yoct9x1#

你的URL看起来不太好。如果你看一下下面的代码:

urlpatterns = [
    path('', views.Add, name = 'add'),       
    path('', views.Delete, name = 'delete'),  <--- url path same as above 
]

但是,错误不是来自于此。它是在谈论论点。所以:

urlpatterns = [
    path('add', views.Add, name = 'add'),       
    path('del/<str:id>', views.Delete, name = 'delete'),   
]

现在,您的delete路径将从以下位置获取参数:

<form action="{% url 'todolist:delete' todo.id %}" method="post">

在这里你可以看到更多关于路径。

toiithl6

toiithl62#

Django模板方法(FormClass,TableClass)
(urls.py)

urlpatterns = [
path('label/<int:pk>/delete/',DeleteLabelView.as_view(),name='delete.label'),
]

(Views.py)

class **DeleteLabelView**(DeleteView):
    model = PageLabel
    template_name = '/delete_label.html'
    
    def get_success_url(self):
        return reverse('workspaces:label.list')

我已经在DeleteLabelView中将action.html作为template_name文件传递,而不是需要传递template_name = '/delete_label.html'

这就是为什么我得到这个错误。

相关问题