What you know about URLs and Routes


Recap: Django Routes

Introduction

The Django framework adopts an MVT approach. The model is the data layer of the application. The view layer is responsible for processing the request and returning the response. The template is the presentation layer.

Another crucial component of the Django architecture is the URL dispatcher.

URL dispatcher

The URL dispatcher is equivalent to Controller in the MVC architecture. The urls.py module in the Django project’s package folder acts as the dispatcher. 

It defines the URL patterns. Each URL pattern is mapped with a view function to be invoked when the client’s request URL matches it. 

The URL patterns defined in each app under the project are also included in it.

When the server receives a request in the form of a client URL, the dispatcher matches its pattern with the patterns available in the urls.py and routes the flow of the application toward its associated view.

Suppose a new Django project called littlelemon is created. The urls.py file in the project package shows the following code by default:

#littlelemon/urls.py

from django.contrib import admin
from django.urls import path
 
urlpatterns = [
    path('admin/', admin.site.urls),
]

The code contains a urlpatterns list. And inside the list is a collection of URL routes where each route is constructed with the path() function.

The path() function matches a URL endpoint string with the function you want to be called.

Create Restaurant app

As you develop an app inside the Django project, you must decide which URL patterns you’ll expose to the user and which function you want to execute when each URL is requested.

The functions are defined in the views.py file inside the app package folder.

#restaurant/views.py

from django.http import HttpResponse
 
def sayHello(request):
 return HttpResponse('Hello World')

Suppose that all the routes of the restaurant app will start from /restaurant.

The sayHello() view function from the code snippet in the views.py file above will be called when the user requests the URL path restaurant/.

This mapping is declared in the urls.py module of the app. And you define all the URL routes of the app in this file.

#restaurant/urls.py

from django.contrib import admin 
from django.urls import path 
from .views import sayHello 
  
urlpatterns = [ 
    path('', sayHello, name='sayHello'), 
]

Include app URL configuration in project URL Configuration

Since the urls.py file in the project package is the URL dispatcher, we need to include the routes of the app in it. Update it to contain the following code:

#littlelemon/urls.py

from django.contrib import admin 
from django.urls import path, include  
 
urlpatterns = [ 
    path('admin/', admin.site.urls), 
    path('restaurant/', include('restaurant.urls')),
]

Finally, add the restaurant app to the INSTALLED_APPS list in the littlelemon/settings.py file, run the server and visit the localhost URL http://localhost/restaurant/

Notice that the Hello World message is displayed.


Exercise: Setting up the static routes

Overview

With Django’s powerful Templating language, you can render the HTML pages as the response to a client.

The default Django project template installs the staticfiles app. It provides the functionality for including static assets such as images, JavaScript and CSS files on the web page.

In this exercise, you will define a URL route whose mapped view renders a web page. You will also include an image in the HTML script of the web page.

You can find the resources for these static assets from the link below.

Static routes assets

Scenario

You will be displaying the home page of your web app for your Capstone project application.

Prerequisites

You have already installed the Django framework in a Python virtual environment. You have also created a Django project with LittleLemon as its name, and it has a Django app called restaurant.

Step 1: Create a templates directory

The project package folder and the app package folder both are created inside the outer folder which is identified as BASE_DIR. Inside this BASE_DIR create a template directory/folder named templates.

Step 2: Include the templates directory in settings.py

In VS Code, go to the TEMPLATES section in the settings.py file and ensure that the templates directory created in the above step is in the list of the DIRS attribute.

#Include 'templates' in 'DIRS' attribute
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Step 3: Create index.html

Inside the templates folder, create a new file called index.html and put the following script in it.

<html>
   <head>
      <title>Capstone Project</title>
   </head>
   <body>
      <h1 style="text-align:center;">Welcome ToLittleLemon Restaurant</h1>
   </body>
</html>

Step 4: Define index view

Open the views.py file from the restaurant folder. Add the following function:

from django.shortcuts import render
 
# Create your views here.
def index(request):
    return render(request, 'index.html', {})

Step 5: Add the URL route

Open the urls.py file from the restaurant folder. Make sure that the following path is added to the urlpatterns list.

#define URL route for index() view
from django.urls import path
from . import views
 
urlpatterns = [
    . . . ,
    path('', views.index, name='index')
]

Step 6: Update URLConf

Open the urls.py file from the Littlelemon folder. Include the URL patterns of the restaurant app in it.

#update URLConf by including URL patterns of restaurant app
from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
   path('admin/', admin.site.urls),
   path(restaurant/', include(restaurant.urls'))
]

Step 7: Visit the home page

Run the Django server with the manage.py script and visit the http://localhost:8000/restaurant/ URL.

Step 8: Save the LittleLemon.png image

All the static assets must be placed in the restaurant/static/restaurant folder. Put the littlelemon.png file here.

Step 9: add the static tag in index.html

Modify the index.html file to include the following statements.

<!--add this template tag-->
{% load static %}
<img src="{% static 'restaurant/littlelemon.png' %}">

Step 10: Refresh the home page

You should see the image rendered on the browser.

Conclusion

In this exercise, you successfully rendered a web page with a static image file.


Additional Resources

Here is a list of resources that may be helpful as you continue your learning journey. These resources provide some more in-depth information on the topics covered in this module.

Version control

Django framework


FormStaticDjangoHTMLPython

Previous one 2.Setting up the Project | Next one 4.Models and stored procedures