We previously showed a direct mapping that imported the views.py file into the urls.py file of our projects. So, we were connecting views of our application to the urls.py file of the project itself. However, this solution is not modular. Let’s examine why.

Consider that we have a large scale project that might include various applications. Moreover, the project will also likely have several URL paths, where most paths will be application-specific. So, for a modular solution, we would prefer that the paths specific to an application be declared inside the application folder. This is where the include function will come in and help us out.

The include() function

The include() function allows us to look for a match with the path defined in the urls.py file of our project, and link it back to our application’s own urls.py file. So basically, whenever Django encounters include(), it takes whatever part of the URL matched up to that point and sends the remaining string to the urls.py file of the specified application.

For example, we have an application in our project called profiles. Then, we might have URL paths like:

  1. /profile/admin/<int:id>/
  2. /profile/user/<int:id>/
  3. /home/

Here, the first two are associated with the profiles application, so we want to send them to the urls.py defined inside profiles application folder. Notice that these URLs have the profile at the beginning, which lets us know that they belong to the profiles application. So, we will match the profile part in the project’s url.py and use include() to send the rest of it to the application’s url.py. Consider that before, the path was declared as follows in the project’s url.py:

path('/profile/admin/<int:id>/', profiles.views.admin, name="admin")

Now, it will become:

path('/profile/', include('profiles.urls')

Notice that the include() function takes in the module name as a parameter, where we are sending the rest of the URL to match.

NOTE: We have to manually add the urls.py file in our application because when we start our application, it doesn’t automatically create one for us.

Another example of this is presented in the slides below.

Get hands-on with 1200+ tech skills courses.