首页 > 解决方案 > 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

标签: django

解决方案


这是以这种方式定义 URL 的结果。您首先匹配<noti_id>and 因为noti_id是一个任意字符串,因此它匹配/blog并将DeleteNotificaton视图 bith'blog'称为noti_id.

您可以使您的模式更具限制性,以便pk通过使用<int:…&gt;路径转换器仅接受数字:

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 调用。


推荐阅读