Django 2.0 路径错误 ?: (2_0.W001) 的路由包含 '(?P<',以 '^' 开头,或以 '$' 结尾 [英] Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'

查看:26
本文介绍了Django 2.0 路径错误 ?: (2_0.W001) 的路由包含 '(?P<',以 '^' 开头,或以 '$' 结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我网站上的音乐应用程序创建后端代码.

我已经在我的 views.py 文件中(在正确的目录中)创建了正确的视图,如下所示:

def 详细信息(请求,专辑 ID):return HttpResponse(<h1>专辑 ID 的详细信息:"+ str(album_id) +</h1>")

但是,在为此创建 URL 或路径时(如下所示)

#/music/71/(pk)路径(r'^(?P[0-9])/$', views.detail, name='detail'),

我在我的终端上遇到警告:

<块引用>

?: (2_0.W001) 你的 URL 模式 '^(?P[0-9])/$'[name='detail'] 有一条包含 '(?P<', 以 '^' 开头的路由,或以$"结尾.这可能是迁移到时的疏忽django.urls.path().

并且每当 /music/(路径适用)后跟一个数字,例如 /music/1(这就是我想要的能做)找不到页面,终端提示以上警告.

解决方案

新的 path() Django 2.0 中的语法不使用正则表达式.你想要这样的东西:

path('/', views.detail, name='detail'),

如果要使用正则表达式,可以使用re_path().

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

旧的url() 仍然有效,现在是 re_path 的别名,但将来可能会被弃用.

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

I'm trying to create the back-end code for a music application on my website.

I have created the correct view in my views.py file (in the correct directory) as shown below:

def detail(request, album_id):
    return HttpResponse("<h1>Details for Album ID:" + str(album_id) + "</h1>")

However, when creating the URL or path for this (shown below)

#/music/71/ (pk)
path(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),

I am experiencing a warning on my terminal stating:

?: (2_0.W001) Your URL pattern '^(?P<album_id>[0-9])/$'
[name='detail'] has a route that contains '(?P<', begins with a '^',
or ends with a '$'. This was likely an oversight when migrating to
django.urls.path().

And whenever the /music/ (for which the path works) is followed by a number, such as /music/1 (which is what I want to be able to do) the page cannot be found and the terminal gives the above warning.

解决方案

The new path() syntax in Django 2.0 does not use regular expressions. You want something like:

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

If you want to use a regular expression, you can use re_path().

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

The old url() still works and is now an alias to re_path, but it is likely to be deprecated in future.

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

这篇关于Django 2.0 路径错误 ?: (2_0.W001) 的路由包含 '(?P&lt;',以 '^' 开头,或以 '$' 结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆