Homepage URL

Learn how to add the path and view for the homepage of the Django web app.

Let’s create a home page for our site, so that users can navigate from there to other pages and vice versa.

Add app URLs in the main urls.py

We need to include the URLs from the app that we created in order to be found by the main urls.py file which sits in our project folder. We’ll do this every time that we create a new app.

You can see the urls.py file from the project folder within the code widget at the end of this lesson. We’ve included the path to the URLs of our listings app in line 6. Let’s try to learn about a couple of modules used in urls.py.

The import from django.urls import path in line 2 helps Django look for the variable urlpatterns that points to different paths in the website.

Another import from django.urls import include in line 2 is used by Django to include URLs from different apps inside the project.

Create urls.py for the app

Next step is to create a urls.py file in the app’s directory (listings/) that will match the path set in the urls.py of the project. We have already created this file in the following widget which can be viewed at the path /listings/urls.py.

The screenshot below shows how our app’s directory should look after we create the new urls.py file.

From this point on, we will repeat these steps almost every time we want to create a new page.

Homepage URL path

In the widget below, open urls.py from the app’s folder (/listings/urls.py) to see the code for the homepage URL path.

In line 2, from .import views imports the views from the app’s directory. We need this module because Django maps the URLs to the views and calls the functions in views.py.

In this particular case, the empty string ('') in line 7 matches the base URL for the project which will be our homepage. Django will call the index view which is why we have views.index to specify which view we want to call. On the other hand, name = 'index' is just a way to reference the URL pattern without having to write the entire URL. Instead we can just use the name 'index' to refer to the entire URL.

We already have multiple urls.py files; one for our project and one for our app. We will have another one for another app that we will create, so app_name in line 4 helps Django identify and choose the correct urls.py file from other urls.py files in the project’s directory.

Note: If we run the app at this point, we will get a compilation error because we haven’t added the code for the Homepage view and template. We will add it in the next lesson.

"""
ASGI config for example project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')

application = get_asgi_application()
URLs configuration