How to Map a URL?

  • Users request pages by entering URLs into a browser and clicking a link.
  • To add a homepage URL:
    • Open the file urls.py file in the main code_journal project folder. Here’s the code you’ll see:

code_journal \ urls.py

python
17from django.contrib import admin
18from django.urls import path
19
20urlpatterns = [
21    path('admin/', admin.site.urls),
22]
  • The first two lines import the function and modules that manage URLs for the project and admin site.
  • The body of the file defines the urlpatterns variables.
  • The code at line 21 includes the module admin.site.urls, which defines all the URLs that can be requested from the admin site.

We need to include the URLs for the code_journals app, as shown below:

code_journal \ urls.py

code_journal/urls.py showing the include statement added to route code_journals.urls to the project urlpatterns

  • Here we’ve added a line to include the module code_journals.urls
  • Note the default urls.py file is in the code_journal folder. Now we need to make a second urls.py in the code_journals folder:

code_journals \ urls.py

code_journals/urls.py defining app_name and the index URL pattern using path() mapping the empty string to views.index

  • Note the doc string in line 1 to make it clear which urls.py file we are working in.
  • In line 3 we import the path function, which is needed when mapping URLs to views.
  • In line 5 note that we are importing the views module & the dot tells Python to import views from the same directory that urls.py is currently located.
  • The variable app_name nicely helps distinguish this urls.py file from the other in line 6.
  • The variable urlpatterns in this module is a list of individual pages that can be requested from the code_journals app.
  • The path() function in line 9 takes three arguments:
    • The first argument is a string and helps route the current request properly. The empty string matches the base URL for the project (http://localhost:8000/)
    • The second argument specifies the view function to call. Here we will call views.index.
    • The third argument provides the name index for this URL pattern.