Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

Question:

I know this question has been asked before, but I haven’t found an answer that solves my situation.

I’m looking at the Django tutorial, and I’ve set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://http://localhost:8000/polls/, it gives me this error:

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^% [name='index']
^admin/
The current URL, polls/, didn't match any of these.

I’m using Django 1.10.5 and Python 2.7.

Here is the code I have in relevant url and view files:

In mysite/polls/views.py:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
  return HttpResponse("Hello, world. You're at the polls index.")

In mysite/polls/urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
  url(r'^%', views.index, name='index'),
]

In mysite/mysite/urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

What’s going on? Why am I getting 404s?

Asked By: HLH

||

Answers:

Your url conf regex is incorrect, you have to use $ instead of %.

from django.conf.urls import url

from . import views

urlpatterns = [
   url(r'^$', views.index, name='index'),
]

The $ acts as a regex flag to define the end of the regular expression.

Answered By: v1k45

urlpatterns = [path('', views.index, name='index'), ]

I ran into the same issue with the tutorial!

The issue is that if you look closely it references two url.py files, mysite/polls/url.py and mysite/url.py.

Putting the provided code in the correct url.py files should correct the issue.

Answered By: 2-sticks

Adding STATIC_URL and STATIC_MEDIA when debug is ON, helped me:

from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    url(r'^$', views.index, name='index'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Answered By: Vova
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.