试图让它在Django上运行Regex / url / views

问题描述 投票:2回答:1

我是Python和Django的新手,我正在尝试使用PyCharm创建一个url正则表达式,但我不知道为什么它不起作用。

我有这个例子......

from django.contrib import admin
from django.urls import path
from .views import (home, client_detail,)

urlpatterns = [
   path(r'^$', home),
   path(r'^/cliente/(?P<id>\d+)/$', client_detail),
   path(r'admin/', admin.site.urls),
]

我有一个views.py,其中包含以下代码:

from django.http import HttpResponse

def home(request):
    return HttpResponse('HOME')

def client_detail(request, id):
    return HttpResponse(id)

问题是:当我写path(r'^/cliente/(?P<id>\d+)/$', client_detail)而不是path(r'/cliente/<id>', client_detail)时,我收到下面的打印错误

有人可以告诉我我错过了什么吗?提前致谢! :)

Error

python regex django url pycharm
1个回答
2
投票

你正在使用path,但你的模式是一个正则表达式。然后使用re_path

https://docs.djangoproject.com/en/2.1/ref/urls/#re-path

re_path(r'^/cliente/(?P<id>\d+)/$', client_detail),
© www.soinside.com 2019 - 2024. All rights reserved.