Adding a new URL makes the root URL not found (404)

Hello,

I’m just getting started with Django and going through the official tutorial (polls app).

After installing Django, if I go to localhost:8000, a startup page is shown. Following the official tutorial, I’ve added the URL for the polls. The localhost:8000/polls/ is displaying as expected.

But the startup page (with the rocket image) is not appearing, rather it’s showing 404 not found.

I’m curious why this is happening? If anyone could explain, it would be very helpful for me.

1 Like

If you create any route at all, the default page will no longer show.

You can create a view for the empty path path(“”, ...), which will respond to the homepage /

I hope that makes sense.

1 Like

Thank you for the prompt reply :slight_smile:

Maybe I’m belaboring the point here, but I’m just going through the tutorial and so I can illustrate in a bit more detail what carltongibson described.

This is what your project ROOT_URLCONF (as defined in your ‘settings.py’ file) urls.py file probably looks like:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls'))
]

You only have urlpatterns that describe what should happen/where the user should be directed when the user goes to (as in your example) localhost:8000/polls/ (path('admin/', admin.site.urls) ) or localhost:8000/polls/ (path('polls/', include('polls.urls')) ). Django doesn’t know what to do if the user goes to any other site URL, other than returning a 404 missing page error. This includes the URL localhost:8000/. Django looks in the urlpatterns list but doesn’t find a matching pattern. If you want something to happen when the user goes to localhost:8000/ , you need to add the matching pattern, like this:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
    path('', <WHATTODO>)
]

If you want to turn it into a workable example and see what happens yourself, you can do e. g. this:

from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
    path('', lambda request: HttpResponse('the cow jumped over the moon')),
]

If you visit localhost:8000 you should see the message ‘the cow jumped over the moon’. If you haven’t used Python much before the lambda part might be confusing to you. Don’t worry, that’s not really important and you’ll learn it in time. You could just as well replace the lambda stuff with a view you’d define somewhere else and import to this urls.py file, just like you import views to the polls/urls.py file.

Hope this helps you understand, otherwise just keep going and it will probably become clearer in time :slight_smile:

5 Likes