django - Django Field 'id' 需要一个数字,但得到了 '.....'。如果 url 末尾缺少正斜杠,则会出现此错误
问题描述
在我的视图中添加删除功能后,我遇到了这个错误。如果像这样的任何 url 的末尾缺少正斜杠,"http://127.0.0.1:8000/blog"
那么我会收到此错误 。Field 'id' expected a number but got 'blog'.
如果我键入http://127.0.0.1:8000/blog/
,那么它将带入我的博客页面。例如,我试图像这样访问我的管理页面,http://127.0.0.1:8000/admin
然后它会给我同样的错误Field 'id' expected a number but got 'admin'.
这个错误发生在我的所有 url 上。在我的视图中添加此删除功能后,我收到此错误:
def DeleteNotificaton(request,noti_id):
user= request.user
if user.is_authenticated:
author = Blog.objects.filter(author=user)
if not author:
Notifications.objects.filter(id=noti_id,receiver=user).delete()
Notifications.objects.filter(id=noti_id,sender=user).delete()
messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.')
return redirect('notifications:notify')
if author:
Notifications.objects.filter(id=noti_id,receiver=user).delete()
messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.')
return redirect('notifications:notify_author')
return redirect('http://127.0.0.1:8000/admin/')
如何解决这个任何想法?
我的网址.py
from django.urls import path,include
from notifications import views
from .views import *
app_name = 'notifications'
urlpatterns = [
path('notifications/',views.ShowNOtifications,name='notify'),
path('author-notifications/',views.ShowAuthorNOtifications,name='notify_author'),
path('<noti_id>',views.DeleteNotificaton, name='delete-noti'),
]
控制台错误:
ValueError: Field 'id' expected a number but got 'blog'.
[25/Jul/2021 23:51:21] "GET /blog HTTP/1.1" 500 134098
解决方案
这是以这种方式定义 URL 的结果。您首先匹配<noti_id>
and 因为noti_id
是一个任意字符串,因此它匹配/blog
并将DeleteNotificaton
视图 bith'blog'
称为noti_id
.
您可以使您的模式更具限制性,以便pk
通过使用<int:…>
路径转换器仅接受数字:
from django.urls import path,include
from notifications import views
from .views import *
app_name = 'notifications'
urlpatterns = [
path('notifications/',views.ShowNOtifications,name='notify'),
path('author-notifications/',views.ShowAuthorNOtifications,name='notify_author'),
path('<int:noti_id>',views.DeleteNotificaton, name='delete-noti'),
]
注意:HTTP 协议的第 9 节 规定,像 GET 和 HEAD 这样的请求不应有副作用,因此您不应使用此类请求更改实体。通常 POST、PUT、PATCH 和 DELETE 请求用于此目的。在这种情况下,您制作一个
<form>
会触发 POST 请求的小程序,或者您使用一些 AJAX 调用。
推荐阅读
- java - VBO 和 VAO 不绘制 opengl 和 LWJGL3
- ruby - Ruby Regex:如何在方括号内匹配(命名)组?
- android - 导航架构组件 - 如何刷新片段?
- mysql - 'unsigned int ..' 附近的未知 CREATE TABLE 语法错误
- database - 一致哈希中的不可用节点
- tensorflow - 使用时间分布式包装器使用 keras 结合 cnn 和 LSTM 时的问题
- c# - C# WPF 截图应用程序——通过鼠标事件处理画布上的绘图
- html - 基于函数返回显示不同元素的正确方法是什么
- java - 分页找不到当前位置
- javascript - 读取 obj/array 到 html