django rest url 中傳入參數 無法識別 404問題


Django 3.0.2  
djangorestframework 3.11.0  

在創建新的djaong_rest fram work項目的時候

啟動django項目報錯如下

D:\work\djc_wcapp\djc_wcapp\app\urls.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified some issues:

WARNINGS:
?: (2_0.W001) Your URL pattern '^gamefile$' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path().
?: (2_0.W001) Your URL pattern '^gamefile/(?P<gm_id>\d+)$' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.
urls.path().

url.py中的文件如下

"""djc_wcapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from app import views


urlpatterns = [
    path(r'^gamefile/(?P<gm_id>\d+)$', views.GameFileDBDeatailView.as_view()),  # 增刪改查
    path(r'^gamefile$',views.GameFileDBView.as_view()), #增刪改查
]

訪問對應的url

提示如下

Django version 3.0.2, using settings 'djc_wcapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /api/v1/gamefile/1
[23/May/2020 13:40:25] "GET /api/v1/gamefile/1 HTTP/1.1" 404 2342
Not Found: /api/v1/gamefile
[23/May/2020 13:40:31] "GET /api/v1/gamefile HTTP/1.1" 404 2336

原因:Django 2.0中的新path()語法不使用正則表達式.你想要的東西:

 url.py修改為re_path

from django.contrib import admin
from django.urls import path,re_path
from app import views


urlpatterns = [
    re_path(r'^gamefile/(?P<gm_id>\d+)$', views.GameFileDBDeatailView.as_view()),  # 增刪改查
    re_path(r'^gamefile$',views.GameFileDBView.as_view()), #增刪改查
]

 

Django 2.0中的新path()語法不使用正則表達式.你想要的東西:

 

path('<int:album_id>/', views.detail, name='detail'),

如果要使用正則表達式,可以使用re_path().

 

re_path(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),

舊的url()仍然有效,現在是re_path的別名,但將來可能會被棄用.

 

url(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM