Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'

不羁的心 提交于 2019-11-27 01:44:54

问题


I'm new to Django and am 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.

It may be a simple error and just me being stupid but I'm new to Django and python regex statements, so any help is appreciated.


回答1:


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'),



回答2:


Just to add to what @alasdair mentioned, I added re_path as part of the include and it works fine. Here is an example

Add re_path to your import (for django 2.0)

from django.urls import path, re_path

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$', home, name='home'),

]



回答3:


Instead of using 're_path' you can also use ''(empty string) as the first argument of your path(). I have used it and it worked for me.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
]



回答4:


Use an empty string '' instead of '/' or r'^$'. It works like a charm. Code is as below:

from django.urls import path, re_path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
]



回答5:


If it doesn't work add this code to yoursite\urls.py inside urlpatterns:

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


来源:https://stackoverflow.com/questions/47661536/django-2-0-path-error-2-0-w001-has-a-route-that-contains-p-begins-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!