Routing in Django

Building web applications with Python & Django

🕑 This lesson will take about 20 minutes

In Django, routing refers to the way that Django matches an incoming web request to a particular view. In other words, if a user requests a particular URL or performs a particular action, then a particular section of code will be executed. This process is handled by URL patterns that map requests to view functions or class-based views.

Here's how it works:

  • Django uses a URL configuration file (or urlconf) to define all the possible routes in the application. It defines which views are called based on requested URLS or actions performed by users. This file is called urls.py and is found in each Django app. The main urls.py is located at the project level and can include app-specific URL configurations.

  • Each URL pattern is defined using Django's path() or re_path() function (for regular expressions). These functions map a URL pattern to a view.

URL configuration (urls.py)

Open the urls.py file in your app folder (eg. myapp). Make sure you open that and not the one in the project folder. There will already be some code from earlier in the course that routes the user to the home page (index) if the home page URL is requested.

Modify the code in the urls.py file (in your app folder, not your project folder) so it now has the following code. This code has a urlpatterns list that specifies which views to load for the user based on URLs that they request. One is for the index (home) page and one is for the about page.

What we have just added needs to be registered globally in our project. You should have performed this step earlier in the course, but to make sure, go to the other urls.py file in your project folder and check that it has the following code (it includes a reference to the app’s URL configuration):

Restart the server (eg. run the command python manage.py runserver or python3 manage.py runserver) and then attempt visiting the index (home) page and the about page in the app. For example, go to the following URLs (the address might vary for your web server):

For each of the two URLs, the web server should run the views you created earlier and use the HTML templates you created earlier to display the right content to you.

The home page
The about page