【问题标题】:Trying to make it work Regex/url/views on Django试图让它在 Django 上工作 Regex/url/views
【发布时间】:2019-02-06 17:52:00
【问题描述】:

我是 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&lt;id&gt;\d+)/$', client_detail) 而不是path(r'/cliente/&lt;id&gt;', client_detail) 时,我收到下面的打印错误

谁能告诉我我错过了什么?提前致谢! :)

Error

【问题讨论】:

    标签: python regex django url pycharm


    【解决方案1】:

    您正在使用path,但您的模式是正则表达式。然后使用re_path:

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

    re_path(r'^/cliente/(?P<id>\d+)/$', client_detail),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 2021-04-12
      相关资源
      最近更新 更多