Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Error: Your URL pattern is invalid. Ensure that urlpatterns is a list of url() instances

After upgrading to Django 1.10, I get the following error when I run python manage.py runserver:

?: (urls.E004) Your URL pattern ('^$', 'myapp.views.home') is invalid. Ensure that urlpatterns is a list of url() instances.
HINT: Try using url() instead of a tuple.

My urlpatterns are as follows:

from myapp.views import home

urlpatterns = [
    (r'^$', home, name='home'),
]
like image 644
Alasdair Avatar asked Aug 05 '16 09:08

Alasdair


People also ask

What is URL pattern in 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).

When should one use the include () in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

What is the use of the include function in the urls py file in Django?

include() A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified.

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.


1 Answers

To simplify URL configs, patterns() was deprecated in Django 1.8, and removed in 1.10 (release notes). In Django 1.10, urlpatterns must be a list of url() instances. Using a tuple in patterns() is not supported any more, and the Django checks framework will raise an error.

Fixing this is easy, just convert any tuples

urlpatterns = [
    (r'^$', home, name='home'),  # tuple
]

to url() instances:

urlpatterns = [
    url(r'^$', home, name='home'),  # url instance
]

If you get the following NameError,

NameError: name 'url' is not defined

then add the following import to your urls.py:

from django.conf.urls import url

If you use strings in your url patterns, e.g. 'myapp.views.home', you'll have to update these to use a callable at the same time. See this answer for more info.

See the Django URL dispatcher docs for more information about urlpatterns.

like image 105
Alasdair Avatar answered Sep 28 '22 04:09

Alasdair