Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 361
Joe Tynan Avatar asked Dec 05 '17 19:12

Joe Tynan


People also ask

How will you declare a route in Django?

To create a route in Django, we will use the path() function that accepts two parameters: a URL and a View function. All the routes are created inside the urlpatterns list. Simply add a new path as below and a new route will be created.

What does path do in Django?

The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.

What happens when a URL is matched Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).


2 Answers

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'), 
like image 63
Alasdair Avatar answered Sep 20 '22 17:09

Alasdair


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'),  ] 
like image 37
Stryker Avatar answered Sep 23 '22 17:09

Stryker