我正在按照教程制作待办事项列表网站。在尝试实现删除按钮时,我遇到此错误。
找不到页面(404)请求方法:GET请求 网址:http://localhost:8000/%7B%25%20url%20'删除'%20things.id%20%25 Django使用todo.urls中定义的URLconf,尝试了这些URL 模式,按此顺序: admin / [name ='home'] delete /“” [name ='delete']当前 路径,{%url'delete'things.id%,与任何这些都不匹配。
相关代码: views.py
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
# Create your views here.
def home(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request, ('Item Has Been Added To List!'))
return render(request, 'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'home.html', {'all_items': all_items})
def delete(request, list_id):
item = List.objects.get(pk=list_id)
item.delete()
messages.success(request, ('Item Has Been Deleted!'))
return redirect('home')
home.html
<tr>
<td>{{ things.item }}</td>
<td><center>{{ things.completed }}</center></td>
<td><center><a href = "{% url 'delete' things.id %}"> Delete</a></center></td>
</tr>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('delete/<list_id>', views.delete, name="delete"),
]
答案 0 :(得分:1)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('delete/<int:list_id>/', views.delete, name="delete"),
]
您需要在网址中指定int
类型。
还有结尾的/
答案 1 :(得分:1)
您需要一个正则表达式来表示一个数字
path('delete/(?P<list_id>)[\d]+)/$', views.delete, name="delete"),