0% found this document useful (0 votes)
31 views90 pages

Python For Django Framework

This document provides an introduction to the Django framework, highlighting its features, installation process, and how to create a basic web application. It covers the differences between Django and Flask, the types of applications suitable for Django, and includes practical exercises for setting up a Django project and app. Additionally, it explains key concepts such as views, URL mapping, and project structure, culminating in the creation of a 'Hello, world!' application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views90 pages

Python For Django Framework

This document provides an introduction to the Django framework, highlighting its features, installation process, and how to create a basic web application. It covers the differences between Django and Flask, the types of applications suitable for Django, and includes practical exercises for setting up a Django project and app. Additionally, it explains key concepts such as views, URL mapping, and project structure, culminating in the creation of a 'Hello, world!' application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 90

PYTHON FOR DJANGO FRAMEWORK

Introduction:

Django is a popular server-side web framework. Its primary focus is


around data-driven websites with commonly needed utilities prebuilt
into the platform. Django is built on Python. It offers flexibility and a
collection of community-built extensions.

This module introduces you to Django. To help you understand the


Django framework, we'll take you through the types of applications
that are best suited for deployment, installation, and creating your first
program.

In this module you'll learn:

 Why Django is great for quick deployment of web applications.


 The difference between Django and Flask.
 What types of applications are best for Django.
 How to install Django.
 How to create a website in Django.

Prerequisites

 Visual Studio Code


 Git
 Understanding of HTML and CSS
 Intermediate-level knowledge of Python, including:
o Package management
o Virtual environments
o Inheritance
What is Django?

Django, pronounced "jango," is a free and open-source framework that


was first released in 2005. Django was named after the famous jazz
guitarist Django Reinhardt. Over the years, many Python frameworks
have been developed, but Django has become one of the most popular
because of its flexibility and security.

Django is suitable for both front-end and back-end web development.


The integrated Python libraries make it easy for rapid development.
Django has become widely accepted across industries. Because of its
growing popularity, providers are more readily available to support
Django applications on their platforms.
Application types

Django offers a complete framework solution, which means it provides


everything you need to quickly deploy your projects. Django offers
great out-of-the-box security, a vast community of users, and can scale
on demand. For these reasons, it's considered a framework of choice
by many developers. By using Django, you can develop complex and
database-driven web applications that can include:

 Machine learning
 E-commerce platforms
 Data analysis
 Content management

Django vs. Flask

While both of these frameworks could suit the needs of your next
Python application, there are specific functionalities and levels of
support that each provides. Let's quickly go through the differences.

Expand table

Django Flask

Full-stack framework Lightweight web framework

Ideal for data-driven applications Ideal for existing APIs and services

Potentially more of a learning curve Potentially less of a learning curve

Out-of-the-box security Additional libraries needed for security

Custom HTML templating engine Jinja HTML templating engine

Django and Flask both offer great benefits for your projects. Depending
on the time requirements for app development, one might be better
suited than the other. When you choose a framework, consider the
type and complexity of the application and also the end product.

Exercise - Install Django

Creating a Django project is similar to creating any Python application.


We start by creating a folder, and then we install the package by
using pip.
Installation overview

Before you install Django, first make sure the correct Python version is
installed for the framework. To check your installed version, go to your
command prompt and enter the following command:

# Windows
python --version

# macOS or Linux
python3 --version

After the command runs, the Python version that's installed on your
computer appears. For this module, we're using the latest official
version of Django. Use Python 3 for access to the latest Python
features. If you don't have Python installed, go to the Python website to
download the correct version.

Create the project folder

Before you download Django, create a virtual environment to isolate it


from other applications. If a virtual environment isn't created and the
framework is installed globally, it could cause a conflict with other
Python applications and cause them to fail.

Start by creating a folder to contain the new project. It will also hold
the folder for the virtual environment.

1. Open a command or terminal window.

2. Create a new directory named hello_django, and change


directories into it.

# Windows
md hello_django
cd hello_django

#macOS or Linux
mkdir hello_django
cd hello_django

3. Open the folder in Visual Studio Code by using the following


command:

code .
Create and activate the virtual environment

We'll use the integrated terminal in Visual Studio Code to avoid


changing windows while we run the necessary commands to create the
resources we need. We'll start by creating a virtual environment and
activating it.

1. Inside Visual Studio Code, select Terminal > New Terminal.

2. Inside the terminal window at the bottom of Visual Studio


Code, run the following commands to create and activate your
virtual environment.

# Windows
python -m venv venv
.\\venv\\Scripts\\Activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate

The name of the virtual environment will be in parentheses


followed by the path that you're in currently. This command
prompt is where you'll begin to install the Django framework.

Django installation

The most common way to manage Python packages is by using


a requirements or requirements.txt file. The requirements.txt file
lists the packages your application uses. Let's create
our requirements.txt file, add Django, and then install the library.

1. Inside Visual Studio Code, create a new file


named requirements.txt inside your hello_django folder.

2. Add the following text to requirements.txt.

Django

3. Inside the terminal window, run the following command to install


Django and any other packages listed in requirements.txt.

pip install -r requirements.txt

With this command, the Django framework will begin to download.


After the download is finished, we can start developing our app.

Explore basic concepts in Django


Now that Django is installed, let's examine some key concepts and
discover the difference between a project and an app.

Projects vs. apps

Project App

There's only one project. There can be many apps within the single projec

Contains the necessary settings or apps for a specific website. Is a component of the larger we

Projects aren't used in other projects. Apps can be used across multipl

Views

Views are another component of Django apps that serve a specific


function within the app. Views contain all the necessary code that will
return a specific response when requested, such as a template or an
image. They can even redirect to another page if the request doesn't
follow the necessary logic within the function.

URL mapping

URL mapping in Django is called URLconf and serves as a table of


contents for your app. After a URL is requested, this module finds the
appropriate link within the project and redirects the request over to the
views file contained within the app. The view then processes the
request and performs the necessary operations.

As you continue to learn and have more complex file structures, you'll
add more views and URLs for your app. The URLconf function plays a
key role because it allows for a simple way to manage and organize
URLs within the application. It also provides greater freedom to change
path roots without breaking the app.

Exercise - Create your first project


Now that we've explored some basic concepts of Django, let's begin
creating the project.
Create a project with Django-admin

As highlighted previously, a Django project is the container for our


entire project and any applications we create. Let's create our project.

Inside the terminal window in Visual Studio Code, run the following
command:

BashCopy
django-admin startproject helloproject .
Important

The trailing period at the end of the command is important. It


instructs django-admin to use the current folder. If you leave off the
period, it will create an additional subdirectory.

After you run the preceding command, the new project should now be
in your chosen directory. In this instance, you would see a new folder
called helloproject.

Explore the project structure

Now that the Django project has been created, let's look at the
structure to see what was included.

textCopy
manage.py
helloproject/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py

 The command-line utility manage.py is created in every Django


project. It has the same function as django-admin. The following
example shows how it could be used if you were inside the project
folder and wanted to see the available subcommands.

BashCopy
python manage.py help

 helloproject is considered the Python package for your project.

 init.py is an empty file that functions to tell Python that this


directory should be considered a package.
 settings.py contains all of your settings or configurations.

 urls.py contains the URLs within the project.

 asgi.py and wsgi.py serve as the entry point for your web
servers depending on what type of server is deployed.

Run the project

Now that Django is installed, a project has been created, and we've
examined the project structure, it's time to make sure our project is
working correctly.

1. Inside the terminal window in Visual Studio Code, enter the


following code to start the server.

BashCopy
python manage.py runserver

The project performs system checks and starts your development


server. Copy and paste the URL of your development server, which
should be http://localhost:8000, into your preferred browser. You
should see a Django Congratulations page with an image of a
rocket taking off.

2. Stop the server temporarily, because we'll need to reconfigure our


project. Inside the terminal window, select Ctrl+C.

Create the Hello World app

We've learned the basics about the Django framework and examined
the folder structure of our project. Now it's time to create our first app!
The Hello, world! app will help you understand how apps are created
and how they work in unison with the Django project.

Inside the terminal window, run the following command to create the
app.

BashCopy
python manage.py startapp hello_world

With this command, Django creates the required folders and files, and
the following structure should now be visible.

textCopy
hello_world/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

Register app with project

Because apps and projects are separate in Django, you must register
your app with the project. This is done by updating
the INSTALLED_APPS variable inside settings.py for the project, adding a
reference to the config class for the app. The config class is found
in apps.py, and is the same name as the project. In our example, the
class will be named HelloWorldConfig.

1. Inside helloproject, open settings.py.

2. Find the list INSTALLED_APPS, which should be in line 33.

3. Add the following to the end of the list, inside the square brackets
([ ]):

PythonCopy
'hello_world.apps.HelloWorldConfig',

4. The updated INSTALLED_APPS list should look like the following:

PythonCopy
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello_world.apps.HelloWorldConfig',
]

5. Save all files by selecting File > Save all.

Congratulations! You've now created your first Django project and app.
Next is to create a path and view to add some functionality.

Understand paths and views


Views and paths (or routes) are core to any web framework. They're
used to determine what information should be displayed to the user
and how the user will access it. Django uses these concepts too.

Paths

All applications allow users to execute different methods or functions


through certain mechanisms. This action might be tapping on a button
in a mobile application or executing a command from the command
line.

In a web application, user requests are made by:

 Navigating to different URLs.


 Typing it in.
 Selecting a link.
 Tapping a button.

A route tells Django what function to execute if the user makes a


request for a particular URL, or path.

A URL like https://adventure-works.com/about might execute a function


called about. The URL https://adventure-works.com/login might execute
a function called authenticate.

Paths in Django are registered by configuring urlpatterns. These


patterns identify what Django should look for in the URL the user is
requesting and determine which function should handle the request.
These patterns are collected into a module Django calls a URLconf.

Views

Views determine what information should be returned to the user.


Views are functions or classes that execute code in response to the
user request. They return HTML or other types of responses, such as a
404 error.

Exercise - Create paths and views


With our app structure created, we can begin to take the steps to add
our own custom code. We'll create a view and then register a path
inside a URLconf.
Create the view

1. Inside Visual Studio Code, open views.py, which will be


inside hello_world.

2. Replace the code inside views.py with the following code:

PythonCopy
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world!")

The helper function HttpResponse allows you to return text or other


primitive types to the caller.

Note

When you open views.py, you might receive a message from


Visual Studio Code that prompts you to install PyLint. If you
receive this message, select Install PyLint.

Create the route

With the view created, the next step is to map it to the appropriate
URL, or path.

1. Inside Visual Studio Code, create a file


in hello_world named urls.py.

2. Add the following code to the new urls.py.

PythonCopy
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
]

The most important part of this code is the urlpatterns tuple. This tuple
is where the views and URLs are connected or mapped. As you can
see, we've imported our views.py file so we can use it within
the urlpatterns line.
Register our URLconf with the project
Our newly created URLconf is inside our hello_world application.
Because the project controls all user requests, we need to register
our URLconf in the core urls.py file, which is inside helloproject.

1. Open urls.py inside helloproject.

2. Note the doc comments at the beginning. These comments


explain how you can register new URLconf modules.

3. Replace the line that reads from django.urls import path with the
following import statement to add include and path.

PythonCopy
from django.urls import include, path

Using include allows us to import URLconf modules, and path is used


to identify the root for the URLconf.

4. Inside the list, underneath the line that reads urlpatterns = [, add
the following code:

PythonCopy
path('', include('hello_world.urls')),

This code registers our URLconf.

The code underneath the doc comment should now look like the
following sample:

PythonCopy
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('', include('hello_world.urls')),
path('admin/', admin.site.urls),
]

Run your first app

The structure is complete, views were added, and the URLs were
mapped. Now it's time to run your app!
1. Inside the terminal window in Visual Studio Code, run the
following command to start the server again.

BashCopy
python manage.py runserver

2. Open the URL in your preferred browser:

http://localhost:8000/

You should now see Hello, world! in your browser window.


Congratulations! You've created your first Django application.

Exercise - Set up the project and


install Django
Completed100 XP
 2 minutes

In this module, we'll work on a website for dog shelters. This project
focuses on collecting information for all existing dog shelters and the
dogs they're hoping to place across the United States. The fictional
hope for this app is that dogs will be able to find suitable homes faster
because they'll have individuals looking to adopt them from around the
United States and not just their local area.

Django is a good framework for this project because it provides a route


for quickly developing a customer-facing app. It also provides an
established database and admin function that employees can easily
access for quick updating. We've created the initial setup for the
project, so we can focus on the concepts for this module.

Requirements

To complete the exercises, you'll need the following items installed on


your computer:

 Python
 Git
 A code editor such as Visual Studio Code
Clone the starter repository

1. Open a command window or terminal.

2. Run the following commands to clone the starter repository and


change to the project's directory.

BashCopy
git clone https://github.com/MicrosoftDocs/mslearn-django-models-data
cd mslearn-django-models-data/starter
Note

The solution for the exercises can be found in


the solution directory.

Open the project in Visual Studio Code

We'll use Visual Studio Code as our code editor.

In the same command or terminal window, enter the following


command to open the folder in Visual Studio Code:

BashCopy
code .

Create the virtual environment

We'll follow the best practice of working with virtual environments for
our project.

1. Inside Visual Studio Code, open the terminal window by


selecting View > terminal.

2. In the new terminal window, run the following commands to create


and activate a virtual environment:

BashCopy
# Windows
py -3 -m venv venv
.\\venv\\Scripts\\activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate
Install Django

The starter project uses a requirements.txt file to contain the list of all
necessary packages. We can install them by using pip.

In the same terminal window, run the following command to install the
required packages:

BashCopy
pip install -r requirements.txt

Start the server

Django can host the application locally. We'll do this by using the built-
in terminal window in Visual Studio Code.

Enter the following command in the same terminal window:

BashCopy
python manage.py runserver

Django object-relational mapper


Completed100 XP
 2 minutes

Working with a relational database requires a different mindset than


working with objects in an application. Switching between these two
environments can slow the process of creating an application. Also,
converting the results of queries from a database into data that the
application can use requires extra code.

Object-relational mappers, or ORMs, solve this problem by acting as


middleware between an application and the database. You can create
objects that model the data, including adding constraints and other
forms of metadata. The ORM then:

 Manages creating and updating the database as needed.


 Handles the queries.
 Converts (or maps) the requests that you make through your
objects into the appropriate database calls.
Overview of the Django ORM

Django was created for data-driven apps, so it's only natural that it
would have an integrated ORM. The Django ORM will feel natural to
Python developers, because it uses class syntax and inheritance that
you're already familiar with.

Because Django is designed to be a web framework, it can use the


structure of the models that you create to automatically generate
HTML and forms. In most situations, Django can dynamically create the
HTML to allow the user to edit data without requiring us to create the
form manually. It can even manage the database calls for us!

Models in Django
Completed100 XP
 2 minutes

Models are at the heart of any ORM. A model is a representation of


some piece of data that your application will work with. This can be a
person, a product, a category, or any other form of data that your
application needs.

Create a model

In Django, a model is any class that inherits a collection of functionality


from django.models.Model. The collection includes methods that allow
you to query the database, create new entries, and save updates. You
can also define fields, set metadata, and establish relationships
between models.

If you wanted to create two models, Product and Category, you would
add two classes:

PythonCopy
from django.db import models
class Product(models.Model):
# details would go here
pass

class Category(models.Model):
# details would go here
pass
Add methods

Before we discuss how to configure the data for your model, it's
important to highlight the fact that a model is a Python class. As a
result, you can both add methods and override the ones
that Django.models.Model provides, or the ones inherent to all Python
objects.

One method in particular to highlight is __str__. You use this method to


display an object if no fields are specified. If Product has a name field
(which we'll see in just a moment), you can return it as the default
string representation for Product by overriding __str__.

PythonCopy
class Product(models.Model):
name = models.TextField()

def __str__(self):
return self.name

Add fields

Fields define the data structure of a model. Fields might include the
name of an item, a creation date, a price, or any other piece of data
that the model needs to store.

Different pieces of data have different data types, validation rules, and
other forms of metadata. The Django ORM contains a rich suite of
options to configure the fields of your models to your specifications.
The ORM is extensible, so you can create your own rules as needed.

Defining the field type

The core piece of metadata for all fields is the type of data that it will
store, such as a string or a number. Field types map both to a database
type and an HTML form control type (such as a text box or a check
box). Django includes several field types, including:

 CharField: A single line of text.


 TextField: Multiple lines of text.
 BooleanField: A Boolean true/false option.
 DateField: A date.
 TimeField: A time.
 DateTimeField: A date and time.
 URLField: A URL.
 IntegerField: An integer.
 DecimalField: A fixed-precision decimal number.

To add fields to our Product and Category classes, we might have the
following code:

PythonCopy
from django.db import models
class Product(models.Model):
name = models.TextField()
price = models.DecimalField()
creation_date = models.DateField()

class Category(models.Model):
name = models.TextField()

Field options

You can use field options to add metadata to allow null or blank values,
or mark a field as unique. You can also set validation options and
provide custom messages for validation errors.

As with field types, field options map to the appropriate settings in the
database. The rules will be enforced in any forms that Django
generates on your behalf.

Field options are passed into the function for the field itself. Different
fields might support different options. Some of the most common are:

 null
o Boolean option to allow null values.
o Default is False.
 blank
o Boolean option to allow blank values.
o Default is False.
 default
o Allows the configuration of a default value if a value for the field
is not provided.
o If you want to set the default value to a database null,
set default to None.
 unique
o This field must contain a unique value.
o Default is False.
 min_length and max_length
o Used with string types to identify the minimum and maximum
string length.
o Default is None.
 min_value and max_value
o Used with number types to identify the minimum and maximum
values.
 auto_now and auto_now_add.
o Used with date/time types to indicate if the current time should
be used.
o auto_now will always set the field to the current time on save,
which is useful for last_update fields.
o auto_now_add will set the field to the current time on creation,
which is useful for creation_date fields.
Note

The values null and blank can seem similar, but they mean different
things in database terms. null is the lack of a value, whereas blank is
specifically an empty value.

To add options to our models, the code might look like this:

PythonCopy
from django.db import models
class Product(models.Model):
name = models.TextField(max_length=50, min_length=3, unique=True)
price = models.DecimalField(min_value=0.99, max_value=1000)
creation_date = models.DateField(auto_now_add=True)

class Category(models.Model):
name = models.TextField(max_length=50, min_length=3, unique=True)

Keys and relationships

A standard practice in relational databases is for each row in a table to


have a primary key, typically an automatically incremented integer.
Django's ORM will add this key automatically to every model that you
create, by adding a field named id.

If you want to override this behavior, you can set the field that you
want to be your primary key. However, you should rely on
Django's id field in most situations.

Relational databases also have relationships between tables. A product


has a category, an employee has a manager, and a car has a
manufacturer. Django's ORM supports all the relationships that you
might want to create between your models.

The most common relationship is "one-to-many," technically known as


a foreign key relationship. In a foreign key relationship, multiple items
share a single attribute. Multiple products are grouped into a single
category, for example. To model this relationship, you use
the ForeignKey field.
To create the relationship, you add the ForeignKey field to the child
object. If your products are grouped into categories, you add
the category property to the Product class, and you set the type to
be ForeignKey.

Django automatically adds a property to the parent to provide access


to all children called <child>_set, where <child> is the name of the child
object. In our example, Category will automatically
have product_set added to provide access to all products in the
category.

ForeignKey has one mandatory parameter, on_delete. This parameter


tells Django what to do if the parent is deleted. That is, if we delete a
category, what should happen to the products in that category?

The two most common options are:

 CASCADE, which will delete all products if a category is deleted in


our example.
 PROTECT, which will return an error if we try to delete a category
that contains products.
Note

In most situations, you'll want to use PROTECT.

To update our model to create the relationship, we can use the


following code:

PythonCopy
from django.db import models
class Product(models.Model):
name = models.TextField()
price = models.DecimalField()
creation_date = models.DateField()
category = models.ForeignKey(
'Category', #The name of the model
on_delete=models.PROTECT
)

class Category(models.Model):
name = models.TextField()
# product_set will be automatically created

Exercise - Create models


Completed100 XP
 2 minutes

By creating a model, you can define any essential fields and the
behavior of your data. Let's add the necessary models for
the dog_shelters application.
Create models

The first step in the process is to add the models. Django provides an
empty file named models.py that you can use for your models.

1. Open the dog_shelters/models.py file in Visual Studio Code.

2. Add two Python classes to contain the models by entering the


following code under the comment Create your models here:

PythonCopy
# Create your models here
class Shelter(models.Model):
name = models.CharField(max_length=200)
location = models.CharField(max_length=200)
def __str__(self):
return self.name

class Dog(models.Model):
shelter = models.ForeignKey(Shelter, on_delete=models.PROTECT)
name = models.CharField(max_length=200)
description = models.TextField()
intake_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name

By adding these models, we now have a representation for shelters


and dogs. Note the relationship between Dog and Shelter:
a Shelter class can house many Dog values. Also note
the auto_now_add value for intake_date. It automatically sets the field to
the current date if a custom date isn't provided.

We're also using ForeignKey in the Dog class. This part tells Django
there's a relationship between Dog and Shelter. By defining this
relationship, we're telling Django that every dog is related to a single
shelter.

Register the model

All applications must be registered with the project in Django. It might


seem a little counterintuitive, but just because an application folder
exists inside a project doesn't mean it automatically gets loaded. We
need to register it by adding it to the INSTALLED_APPS list.

1. Find the configuration class name within the dog_shelters folder.


To find this class name, go to the dog_shelters/apps.py file and
check that the class name is DogSheltersConfig in the following
code:
PythonCopy
class DogSheltersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'dog_shelters'

2. Open settings.py in project.

3. Add the full path to the class name under the comment #[TODO] -
Add the app to the list of INSTALLED_APPS:

PythonCopy
#[TODO] - Add the app to the list of INSTALLED_APPS
'dog_shelters.apps.DogSheltersConfig',

The INSTALLED_APPS list now contains the following items:

PythonCopy
INSTALLED_APPS = [
#[TODO] - Add the app to the list of INSTALLED_APPS
'dog_shelters.apps.DogSheltersConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Adding the line to the INSTALLED_APPS list tells Django that this app
needs to be included when it runs the project.

Summary

You've now created two models for your Django application. Creating
models is the foundation to all Django projects.

Manage the database


Completed100 XP
 2 minutes

The Django ORM goes beyond allowing you to interact with data. You
can also use it to create and update the database itself through a
process known as migrations.
Migrations

A migration is a collection of updates to be performed on a database's


schema. A database schema is the definition of the database itself,
including all tables and columns, and relationships between those
tables.

When we created our models and defined the fields, we also defined
the tables, columns, and relationships between those tables. We
created our schema definition by creating our models!

Migrations are used to create and update the database as our models
change. As you likely know, software is constantly changing. How we
define our models today might be different from how we define them
tomorrow. Migrations abstract the process of updating the database
away from us. We can then make changes to our models and use
Django to perform the necessary changes to the database.

Make a migration

To create a migration, you use the makemigrations command


in manage.py. The makemigrations command uses the current list of
migrations to get a starting point, and then uses the current state of
your models to determine the delta (the changes that need to be
made). It then generates the necessary code to update the database.
After makemigrations runs, it displays the name of the migration.

BashCopy
python manage.py makemigrations

Display the SQL for the migration

Any operations that happen inside a relational database require


Structured Query Language (SQL). Django's migrations generate the
appropriate SQL when they're run. Although you can use the migration
tools to update your database directly, some environments might have
database administrators who will manage the process for you.

To build the appropriate SQL statements, you can use sqlmigrate.

BashCopy
python manage.py sqlmigrate <app_label> <migration_name>
Note
The app_label part is the name of your app, typically the name of the
folder that contains your app. The migration_name part is the name of
the migration. You can also see the Python code for any app's
migrations in its migrations folder.

Display the list of migrations

If you want to see all migrations, you can use showmigrations.

BashCopy
python manage.py showmigrations

Perform a migration

The migrate command runs a specific migration or all migrations on the


database configured in settings.py in the root of your project folder.

If you open settings.py, you'll see a DATABASES section at the bottom.


This section includes a default option, which on a new project is
configured to use SQLite. You can configure different database
connection strings in this section as needed.

BashCopy
python manage.py migrate <app_label> <migration_name>
Note

The app_label and migration_name parts are optional. If you don't provide
either, all migrations will run. You'll use this command often during
development.

Exercise - Create the database


schema
Completed100 XP
 2 minutes

With our models created, let's create our database. We'll use the
default of SQLite and the tools available through Django.

List all migrations

Let's start by listing all migrations.


In the terminal window for Visual Studio Code, run the following
command:

BashCopy
python manage.py showmigrations

You'll notice a list of migrations. You might wonder why you have
migrations, even though you just started your application and haven't
made any. Django includes various tables for its user management
system, managing sessions, and other internal uses.

Create migrations for dog_shelters


Let's tell Django that new models are added and that we want the
changes to be stored as a migration.

1. Return to the terminal window in Visual Studio Code.

2. Run the following command:

BashCopy
python manage.py makemigrations dog_shelters

After you run the command, you should see code that shows both
models stored as a migration in dog shelters.

Update the database

The migrate command will run all migrations. In the case of SQLite, the
command will even create the database if it doesn't exist. Let's create
our database and perform the migrations.

1. Return to the terminal window in Visual Studio Code.

2. Run the following command:

BashCopy
python manage.py migrate
The migrations that the command runs include the one that we created
and the ones that are built in to Django.

Display the schema

Now that we completed the necessary setup for our SQLite database,
let's use the SQLite Visual Studio Code extension to explore the
created schema.

1. Select the Extensions button on the workbench, and search


for SQLite.

1. Select Install on SQLite.

Note

You might get an error message about being unable to access the
SQLite core process. If this happens, you can install SQLite for
your operating system.
2. Open the command palette by selecting Ctrl+Shift+P on the
keyboard (or Cmd+Shift+P on a Mac).

3. Type SQLite and select SQLite: Open Database.

1. Select db.sqlite3.

2. At the bottom of your workbench on the left side, select the arrow
next to SQLITE EXPLORER.

1. You can now see the list of all the created tables. Expand each one
to view the various columns.

If you explore your shelter and dog tables, you'll notice the
various columns that you created. These columns include id,
which is automatically created on each table.

Summary

You've now managed a database by using Django, deploying any


changes that you made.

Exercise - Work with data


Completed100 XP
 2 minutes
By creating our models, we created an API that we can use to access
the data in our database. This API allows us to create, retrieve, update,
and delete objects in our database.

Let's explore the API by working with the models that we created.

Configure the interactive shell

Django includes an interactive shell where you can run Python code in
the Django environment.

1. Return to the terminal in Visual Studio Code by


selecting View > Terminal.

2. Enter the following command to start the shell:

BashCopy
python manage.py shell

3. Import the models from models inside dog_shelters:

PythonCopy
from dog_shelters.models import Shelter, Dog

Create and modify objects

Because our models are Python classes, we create new instances by


using the same syntax that we'd use to create an object. Because they
inherit from Django.models.Model, they inherit the functionality for the
Django ORM. That functionality includes save, which we use to save the
object to the database.

1. Create a new shelter by running the following Python command in


the shell:

PythonCopy
shelter = Shelter(name="Demo shelter", location="Seattle, WA")
shelter.save()

The save part will write the object to the database. Because we
created this from scratch, it will execute an INSERT statement in
the database.

2. Update the location of the shelter to Redmond, WA, by setting


the location field and calling save:
PythonCopy
shelter.location = "Redmond, WA"
shelter.save()

This command will issue an UPDATE statement to update the value


in the database.

3. Create two new dogs for the shelter by running the following
Python commands in the shell:

PythonCopy
Dog(name="Sammy", description="Cute black and white dog",
shelter=shelter).save()
Dog(name="Roscoe", description="Lab mix", shelter=shelter).save()

As before, save inserts the dog. Notice how we set


the shelter parameter to the shelter object that we created
before. Django will automatically set the relationship in the
database.

Also note that we didn't set up a local variable for


each Dog instance. Because we won't reuse the objects, we don't
need to set them to a variable.

Retrieving objects

To retrieve objects from a database, Django provides


an objects property on all Model classes. The objects property provides
multiple functions, including all, filter, and get.

1. Retrieve all dogs in Demo shelter by running the following


command:

PythonCopy
shelter.dog_set.all()

The dog_set part stores the list of all dogs for a particular shelter.
Django will return a QuerySet object with the two dogs that we
created.

BashCopy
<QuerySet [<Dog: Sammy>, <Dog: Roscoe>]>

2. Retrieve the second dog by using get as shown in the following


command:
PythonCopy
Dog.objects.get(pk=1)

The get function will return only one object. You can pass
parameters into get to provide a query string. Here we use pk,
which is a special keyword to indicate the primary key. The
returned result will be Sammy.

BashCopy
<Dog: Sammy>

3. Retrieve all dogs in Demo shelter by using filter as shown in the


following command:

PythonCopy
Dog.objects.filter(shelter__name='Demo shelter')

Like get, filter allows us to pass a query in the parameters. Notice


we can use two underscores (__) to go from property to property.
Because we want to find all dogs in the shelter named Demo
shelter, we use shelter__name to access the name property
of shelter. The result returned will be all dogs, because we have
only one shelter.

BashCopy
<QuerySet [<Dog: Sammy>, <Dog: Roscoe>]>

Close the shell

After you're done playing with the objects, you can close the shell by
running the exit() command.

Summary

You've now seen how you can programmatically work with data in
Django through the Django ORM.

Introduction to the Django


admin site
Completed100 XP
 2 minutes
When you create applications, you'll eventually want to create
individual permissions for site access. Creating an admin interface for
employees or clients to manipulate content can be a cumbersome task.
Once again Django comes to the rescue with a simple admin feature
that's automatically created in projects. We now continue our journey
through the Django platform by activating the admin site, adding user
permissions, and exploring another view of the database.

In this module, you'll learn how to:

 Enable the admin site.


 Create a super user.
 Add app models and access data.
 Set user permissions.

Prerequisites

 Software
o Visual Studio Code
o Git
 Coding skills
o Understanding of HTML and CSS
o Basic understanding of Django
o Basic understanding of relational databases
o Intermediate-level knowledge of Python, including:
o Package management
o Virtual environments
o Inheritance

Exercise - Get the starter project


Completed100 XP
 6 minutes

In this module, we'll work on a website for dog shelters. This project
focuses on collecting information on all existing dog shelters and the
dogs they hope to place across the United States. The fictional hope for
this app is that dogs would find suitable homes faster because they
would have individuals looking to adopt them from around the United
States and not just their local area.

Django is the perfect framework for this project. It provides a route for
quickly developing a customer-facing app. Django also provides an
established database and admin function that can easily be accessed
by employees for quick updating. We've created the initial setup for
this project, which allows us to focus on the concepts for this module.
Requirements

You'll need the following resources installed on your computer to


complete the exercises:

 Python
 Git
 A code editor such as Visual Studio Code

Clone the starter repository

1. Open a command window or terminal.

2. Run the following commands to clone the starter repository and


change to the project's directory.

BashCopy
git clone https://github.com/MicrosoftDocs/mslearn-django-admin-site
cd mslearn-django-admin-site/starter
Note

The solution for the exercises can be found in


the solution directory.

Open the project in Visual Studio Code

We'll use Visual Studio Code as our code editor.

In the same command or terminal window, enter the following


command to open the folder in Visual Studio Code.

BashCopy
code .

Create the virtual environment

We'll follow the best practice of working with virtual environments for
our project.

1. Inside Visual Studio Code, open the terminal window by


selecting View > terminal.
2. In the new terminal window, run the following commands to
create and activate a virtual environment.

BashCopy
# Windows
py -3 -m venv venv
.\\venv\\Scripts\\activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate

Install Django

The starter project uses a requirements.txt file to contain the list of all
necessary packages. We can install them by using pip.

In the same terminal window, run the following command to install


the required packages.

BashCopy
pip install -r requirements.txt

Create the database

For development purposes, Django uses an instance of SQLite. You can


use Django to create the database through its database migration
tools.

In the same terminal window, run the following command to create


the database.

BashCopy
python manage.py migrate

Start the server

Django can host the application locally. We'll do this step by using the
built-in terminal window in Visual Studio Code.

Enter the following command in the same terminal window.

BashCopy
python manage.py runserver
Permissions for the admin site
Completed100 XP
 4 minutes

Django includes a built-in admin site that can be used to manage the
data in your application and security. This site is part of the default
installation. As we'll see, it requires only a few lines of code to fully
activate it. Django also includes a full authentication and authorization
implementation, which you can use to control access to the admin site.

Security and Django

Django is designed to streamline the creation of data-driven web


applications by providing the normal functionality that's required by
these types of sites. Django provides an authentication and
authorization mechanism, and you're free to expand and modify the
included system. You can incorporate third-party authenticators,
multifactor authentication, or any other requirements your organization
might have. We'll explore the default implementation in this module.

Explore user types

Django has three main types of users by default: users, staff, and
superusers. You can create your own types by making groups or
setting unique permissions.

Access levels

Expand table

Access User Staff

Admin site No Yes

Manage data No No

Manage users No No

By default, staff have access to the admin site but not to modify any
data. You can set individual permissions or create groups as needed to
provide the appropriate levels of access.
Create users

To create users in Django, you must first create a superuser. Use the
command createsuperuser from manage.py to create a superuser.
After you create a superuser, you can access the admin site to create
any other users.

The admin site

Creating a data-driven application means, by definition, working with


data. Allowing internal business users access to modify the data as
they see fit often requires quite a bit of code between security and the
interface. Django provides an admin site that handles this process for
you.

Through the admin site, you can determine which users have access to
what data. Users can then use the admin site to add, update, and
delete items. They don't need to access the database directly or
bypass any of the validation rules you've implemented. The security
model and interface are already created for you as part of the
framework. All you need to do is activate your models so they appear
in the site, which requires only a couple of lines of code.

Exercise - Create users


Completed100 XP
 8 minutes

When you create projects, the admin interface is automatically created,


but it doesn't configure any user access. To sign in to the Django admin
site, we now need to create our first user, which is a superuser.

Create a superuser

1. Open a new terminal window in Visual Studio Code by


selecting Terminal > New terminal.

2. Ensure the virtual environment is activated by running the


following code:

BashCopy
# Windows
.\\venv\\Source\\Activate

# Linux or macOS
source ./venv/bin/activate

3. Create a superuser by running the following command:

BashCopy
python manage.py createsuperuser

4. Complete the process by answering the questions provided by the


wizard. Enter the username you want to use, an email address,
and a password.

Note

The password must be complex according to Django's standards, which


means at least eight characters and a combination of upper- and
lowercase letters, special characters, and numbers. If you don't meet
the complexity rules, Django will ask if you want to override the
requirements, which isn't recommended.

Sign in to the admin site

After the admin user has been created, it's time for our first sign-in to
the Django admin interface. During the project setup earlier in this
module, we started the server, so our admin site is already active.

1. Go to http://localhost:8000/admin.

Enter the username and password you created earlier.


After you've successfully signed in to the admin site, you should see a
screen that looks like the following one.

Select Users.

You'll now see the list of users, which includes the user you created.

Create a staff user

1. Select ADD USER in the upper-right corner.

2. Enter a Username for the staffuser.

3. Enter a Password that meets the complexity requirements, and


confirm the password.

4. Select SAVE.

5. On the next screen, select Staff status to make the new user a
staff user.
1. Select SAVE.

Exercise - Manage data


Completed100 XP
 8 minutes

As highlighted before, the admin site doesn't provide access to your


data by default. Fortunately, it takes only a couple of lines of code to
register any models you want to be editable through the tool.

Register models

1. Open dog_shelters/admin.py.

2. Underneath the comment that reads # Register your models here.,


add the following code to register your models.

PythonCopy
# Register your models here.
from .models import Shelter, Dog

admin.site.register(Shelter)
admin.site.register(Dog)

3. Save the file.

4. Return to your browser, and refresh the page.


Notice that you have Dogs and Shelters listed
under DOG_SHELTERS.

Access our data

With our models registered, we can now manage our data. If there was
any data already in the database, we could modify it as needed.

In our data model, which you can explore by opening models.py, we


have Shelter and Dog. A Shelter contains multiple Dogs to create the
relationship between the models.

Let's create a new Dog to explore how the admin site functions for data.

1. Select Add next to Dogs.

1. Notice that when you select the drop-down list for Shelter, no
shelters are listed because we haven't created one.
Note

If you're continuing with a project you started earlier, you might


see a shelter if you created one.

The drop-down exists so that we can select the shelter into which
we would register the dog. We can create a new one by selecting
the plus sign (+).

2. Select the plus sign (+).

A new window opens where you can create a Shelter.

1. Enter a Name and Location for the shelter, such


as Contoso and Redmond, WA.

2. Select SAVE.

The screen updates and shows the newly created Shelter as the
selected option for the dog.

3. Enter a Name and Description for the dog.

4. Select SAVE.

The screen returns to the list of dogs, and the information on the
newly created dog appears.
1. If you select the dog, you'll be taken to the details page where you
can update any values or delete the entry.

Note

The display shows the name of the dog or the shelter if you go to
the Shelters portion of the admin site. This information appears
because we set the __str__ method on our objects. The default
display of any object is the value returned by __str__.

Exercise - Manage permissions


Completed100 XP
 6 minutes

As highlighted earlier, you can add users with permissions to modify


data through the admin site. Let's update the staffuser user we
created in a prior unit to have permissions to modify dogs.

Set the user permissions

1. Return to the admin site in your browser.

2. Select Users.

3. Select staffuser to update our staffuser.

4. Ensure Staff status is selected.

5. Scroll down to User permissions.

6. Select the following permissions:


 dog_shelters | dog | Can add dog
 dog_shelters | dog | Can change dog
 dog_shelters | dog | Can view dog
Note

The page highlights that you can select multiple permissions by


using Control or Command and selecting each item.

Select Choose.

1. Select SAVE.

Sign in as the staff user

Let's see the difference between a superuser and a staff user by


signing in as a staff user.

1. Select LOG OUT in the upper-right corner.

2. Select Login again.

3. Sign in as staffuser by using the password you created earlier.

Note

If you forgot the password, you can sign in as your superuser and
reset the password.

Notice that the admin page only allows access to Dogs.


1. Select Dogs.

2. Select the dog you created earlier.

Notice that you can modify the dog, but not delete it.

Summary

We've now configured a staff user with limited permissions in the


admin site. You can use this capability to control access to sensitive
data in your application.

Exercise - Get the starter project


Completed100 XP
 5 minutes

In this module, we'll work on a website for dog shelters. This project
focuses on collecting information for all existing dog shelters and the
dogs they're hoping to place. The fictional hope for this app is that
dogs will be able to find suitable homes faster because they'll have
individuals looking to adopt them from around the United States and
not just their local area.

Django is a good framework for this project because it provides a route


for quickly developing a customer-facing app. It also provides an
established database and admin function that employees can easily
access for quick updating. We've created the initial setup for the
project, so we can focus on the concepts for this module.

Requirements

To complete the exercises, you'll need the following items installed on


your computer:
 Python
 Git
 A code editor such as Visual Studio Code

Clone the starter repository

1. Open a command window or terminal.

2. Run the following commands to clone the starter repository and


change to the project's directory.

BashCopy
git clone https://github.com/MicrosoftDocs/mslearn-django-views-
templates
cd mslearn-django-views-templates/starter
Note

The solution for the exercises can be found in


the solution directory.

Open the project in Visual Studio Code

We'll use Visual Studio Code as our code editor.

In the same command or terminal window, enter the following


command to open the folder in Visual Studio Code:

BashCopy
code .

Create the virtual environment

We'll follow the best practice of working with virtual environments for
our project.

1. In Visual Studio Code, open the terminal window by


selecting View > terminal.

2. In the new terminal window, run the following commands to create


and activate a virtual environment:

BashCopy
# Windows
py -3 -m venv venv
.\\venv\\Scripts\\activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate

Install Django

The starter project uses a requirements.txt file to contain the list of all
necessary packages. We can install them by using pip.

In the same terminal window, run the following command to install the
required packages:

BashCopy
pip install -r requirements.txt

Start the server

Django can host the application locally. We'll do this by using the built-
in terminal window in Visual Studio Code.

Enter the following command in the same terminal window:

BashCopy
python manage.py runserver

Get started with views


Completed100 XP
 6 minutes

In programming, a view is typically a component that displays


information to the user. The tasks that a view performs can vary
depending on the framework and conventions, including responsibility
for loading data.

In Django, a view is typically responsible for:

 Validating a user's request.


 Loading or modifying the appropriate data.
 Returning an HTML template with the information to the user.

We're going to begin our exploration by discussing creating views


manually and configuring the appropriate URLconfs. A URLconf is a list
of paths that indicate the pattern to match, the function to call, and
optionally a name. In a later unit, we'll see how Django can
automatically handle some of the code that we wrote by hand.

Create a view

To create a view from scratch in Django, you typically create a


function. The function commonly contains the appropriate code to:

 Perform the task that the user has requested.


 Return a template with the appropriate data to display to the user.

View functions always take at least one parameter named request,


which represents the user's request. You can provide more parameters
as needed if you're expecting more information from the user in the
URL, such as the name or ID of an item. You'll register those when
creating the route, which we talk about later in the unit.

Loading data

You can use the Django ORM to load any data that you need from the
registered database.

The project that we're building has two models, Shelter and Dog. We
can load all objects or perform other queries by using the models that
we created. To load all shelters, for example, we would
use Shelter.objects.all(). We can load an individual shelter by
using Shelter.objects.get(pk=1).

Note

pk is a shortcut for primary key. You can use id and have the same
result, but using pk will ensure that the command works if you've
changed the property that represents the primary key to a different
name.

404 errors

A 404 error in web applications means "not found." As a best practice,


you should return a 404 whenever a request is made for an object that
doesn't exist.

Django provides shortcuts for trying to load data:


 get_object_or_404 and get_list_or_404: Loads an object by a
primary key, or returns a 404 to the user if an object is not found.
 get_list_or_404: Performs the same operation as the other
shortcut, except that it accepts a filter parameter.

We'll use get_object_or_404 in our exercise.

Rendering the template

Django's templating engine will take the HTML template that we build,
combine it with any data that we provide, and emit the HTML for the
browser. The helper function to perform this task is render.

The render function needs the object that represents the request, which
is the request parameter that we highlighted earlier. You also pass in
the name of the template, typically an HTML file that will reside in a
folder named templates.

To pass data into the template, you provide render with


a context dictionary object. The context object contains a set of
key/value pairs, where each key becomes a variable in the template.

Example

To create a view to display all shelters, you might use the following
code:

PythonCopy
def shelter_list(request):
shelters = Shelter.objects.all()
context = { 'shelters': shelters }
return render(request, 'shelter_list.html', context)

Register a path

Almost any web framework uses paths to process user requests. Paths
convert the portion of the URL after the name of the domain and before
the query string (which comes after the question mark) into a function
call.

A call to www.contoso.com/shelters might call a function to list all


shelters, whereas www.contoso.com/shelters/1 might call a function to
display a shelter with an ID of 1. You register paths in Django by
creating a URLconf.
Let's say we have a module called views, which is a Django convention.
We can route index traffic where a path isn't specified (such
as www.contoso.com) to a function in views called index, and give it a
name called index, by using the following path:

PythonCopy
path('', views.index, 'index')

We can also create virtual folders for specific requests. For example, if
we wanted to list all shelters if someone requests /shelters, we could
use the following command:

PythonCopy
path('shelters', views.shelter_list, 'shelter_list')

URL parameters

It's a common practice to pass parameters to an application as part of


the URL, such as an ID or a name. Because these values will change,
we don't want to hard code them into our path. In Django, you can
specify a parameter by using a special syntax. In that syntax, you can
indicate the type of data you're expecting, such as an integer, and a
name.

For example, to create a path for someone to request a specific shelter


by an ID, we would want a parameter of type integer. (The reason is
that our primary key is an integer.) We can then provide the name that
we want to use for the variable, which will then be passed in as a
parameter to the view function. The syntax for identifying this
parameter would be <int:pk>. Notice the type declaration, the colon,
and then the name of the variable.

The full path might look like this:

PythonCopy
path('shelter/<int:pk>', views.shelter_detail, name='shelter_detail')

The associated view function would have the following signature:

PythonCopy
def shelter_detail(request, pk):
# code

The pk part of the path signature is passed into shelter_detail as a


parameter, just as if we were calling it like a normal Python function.
Exercise - Create views
Completed100 XP
 8 minutes

We want to update our application to provide a list of dog shelters. We


also want the application to allow someone to click or tap an individual
shelter to see the details. We'll do this by creating two views and then
registering the appropriate paths.

Create views

1. In Visual Studio Code, open dog_shelters/views.py.

2. At the end of the line that reads from django.shortcuts import


render, add , get_object_or_404. The line should now read:

PythonCopy
from django.shortcuts import render, get_object_or_404

3. Below the line that reads from django.shortcuts import render, add
the following Python code to import your models:

PythonCopy
from . import models

4. At the end of views.py, add the following code to load all shelters,
create the context object for the template, and then render the
template for the user. This will become our list view for shelters
and the default page for our site.

PythonCopy
def shelter_list(request):
shelters = models.Shelter.objects.all()
context = {'shelters': shelters}
return render(request, 'shelter_list.html', context)

5. At the end of views.py, add the following code to load a specific


shelter by its pk or primary key, create the context object for the
template, and then render the template for the user. This will
become the details page for a shelter.

PythonCopy
def shelter_detail(request, pk):
shelter = get_object_or_404(models.Shelter, pk=pk)
context = {'shelter': shelter}
return render(request, 'shelter_detail.html', context)

Create the URLconf

For our views to be callable, we need to register the appropriate paths.

1. Create a new file in dog_shelters called urls.py.

2. Add the following code to register the paths for the two views that
we created:

PythonCopy
from django.urls import path
from . import views

urlpatterns = [
path('', views.shelter_list, name='shelter_list'),
path('shelter/<int:pk>', views.shelter_detail,
name='shelter_detail'),
# More patterns to come later
]

Notice that we created a default path ('') to point to


our shelter_list view. We also registered shelter/<int:pk> to reference
our shelter_detail view. As highlighted earlier, pk will be passed as
the pk parameter to shelter_detail.

Register URLconf with our project

Django uses one core urls.py file as its URLconf. As a result, we need to
ensure that the one we created is properly registered.

1. Open project/urls.py.

2. Toward the bottom of the file, find line 17, which reads:

PythonCopy
from django.urls import path

At the end of the line, add , include. The new line 17 should now
be the following:

PythonCopy
from django.urls import path, include

3. Below the line that reads TODO: Register URLconf, add the following:
PythonCopy
# TODO: Register URLconf
path('', include('dog_shelters.urls')),
Important

The trailing comma is required.

4. Save all files by selecting File > Save All.

Get started with Django


templates
Completed100 XP
 7 minutes

Templates are text files that can be used to generate text-based


formats such as HTML or XML. Each template contains some static data
that's shared across the site, but it can also contain placeholders for
dynamic data. Templates contain variables and tags that control the
behavior and what will appear as the final page.

Let's explore how templates work in Django.

Variables

Variables in a template behave as they do in any other programming


language. We can use them to indicate a value that's evaluated at
runtime.

Django provides a way to display variables in a template by using


the {{ }} syntax. Any variable placed inside the double curly braces is
evaluated for its text content and then placed into the template. If we
wanted to display the dog's name, for example, we could
use {{dog.name}}.

The view passes variables into a template by using the render function,
which we'll explore in a later module. You can pass values and other
data to a template, including a QuerySet from the Django ORM. This
allows you to display data from the database for your application.

Filters

Filters are a great way to control how the data appears when it's
requested in a template. Because filters are already created, they
provide an easy way for you to format data without having to write any
special code.

For example, let's say we have to print out the names of the dog
breeds, and we want to make sure the first letter of every name is
capitalized.

HTMLCopy
{{ dog.name | capfirst }}

The variable is to the left of the pipe symbol ( |), and the filter is on the
right. This is just one of many filters that you can use to manipulate the
data when you're using Django template filters.

Tags

You can use tags to perform loops, create text, or provide other types
of commands for the template engine. Tags often resemble Python
syntax. But because they run inside the template (rather than inside
the Python interpreter), you'll notice some slight differences in syntax.
Without the ability to rely on tabs like we would with Python, each
block statement will require a corresponding end.

We can use if statements for Boolean logic, and for loops for iteration.
The core syntax for if statements looks like the following:

HTMLCopy
{% if dogs %}
<h2>There are {{ dogs | length }} ready for adoption!</h2>
{% else %}
<h2>We have no dogs ready for adoption. Please check back later!</h2>
{% endif %}
Note

The elif statement is used in the same way as elif in Python.

Similarly, we can use a for loop to display the names of all dogs in a
list:

HTMLCopy
<ul>
{% for dog in dogs %}
<li>{{ dog.name }}</li>
{% endfor %}
<ul>
Template inheritance

Templates are used to generate the HTML that you want the user to
see while using your application. Pages in an application typically share
a common structure, where navigation might be on the left, a title is on
the top, and there's a consistent stylesheet. Django templates support
shared structures through inheritance.

Create a parent page

Creating a parent page is the same as creating any Django HTML


template. You provide the outer structure and then include {% block
%} placeholders. These placeholders allow the children to provide the
content to be placed in those placeholders.

Let's create a parent page to import a stylesheet, provide a default


title, and provide a header that we want to display on all pages:

HTMLCopy
<html>
<head>
<link rel="stylesheet" href="site.css">
<title>{% block title %}Shelter site{% endblock %}</title>
</head>
<body>
<h1>Shelter site</h1>
{% block content %}
{% endblock %}
</body>
</html>

Create a child page

We can create a child page from the parent by using


the extends keyword. With this keyword, we provide the name of the
HTML file of the parent template. We then use the appropriate {% block
%} statements to add the content specific to that page.

HTMLCopy
{% extends "parent.html" %}

{% block title %}
Welcome to the Shelter site!
{% endblock %}

{% block content %}
Thank you for visiting our site!
{% endblock %}
When the page is displayed, it looks like the following:

HTMLCopy
<html>
<head>
<link rel="stylesheet" href="site.css">
<title>Welcome to the shelter site</title>
</head>
<body>
<h1>Shelter site</h1>
Thank you for visiting our site!
</body>
</html>

Notice how the placeholders are replaced by the content in the child
page.

Note

For this example, we used static text. As you'll see, you can also use
dynamic content.

Exercise - Create templates


Completed100 XP
 6 minutes

Let's create two templates to display a list of shelters, and a detail


page for each shelter. We'll also create a base template to ensure
consistency across our application.

Create the base template

A base template is common for all Django projects. We'll start by


creating one.

1. In Visual Studio Code, create a new folder


inside dog_shelters named templates.

2. Create a new file inside templates named base.html.

3. Add the following HTML to base.html:

HTMLCopy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>{% block title %}Dog shelter site{% endblock %}</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.
min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUF
pCjEUQouq2+l" crossorigin="anonymous">
</head>
<body>
<article class="container">
<section class="jumbotron">
<h3>Dog shelter application</h3>
</section>
{% block content %}
{% endblock %}
</article>
</body>
</html>
Note

We're using Bootstrap version 4.6 for our site. We don't need
Bootstrap knowledge here, though. We're using only one
class, jumbotron. Otherwise, we're using core HTML.

Notice the two {% block %} statements, one for the title and the next for
the content that the child pages will provide. We're providing a default
value for title, which ensures that we'll always have a title if a child
page doesn't set it.

Create the shelter list template

We'll now create another template for listing all shelters. We'll loop
through the list of shelters and create links to details for all shelters.

1. In dog_shelters/templates, create a new file


named shelter_list.html.

2. Add the following code to create the template for our shelter list:

HTMLCopy
{% extends 'base.html' %}

{% block title %}
Shelter list
{% endblock %}

{% block content %}
<h2>Shelter list</h2>
<div>Here is the list of registered shelters</div>
{% for shelter in shelters %}
<div>
<a href="{% url 'shelter_detail' shelter.id %}">
{{shelter.name}}
</a>
</div>
{% endfor %}
</div>
{% endblock %}

We use the block tags to indicate where we want our information to be


placed. We specify a title value of Shelter list, and the content items
will be the list of all shelters.

We're also using a new tag, url. The url tag generates a URL
dynamically. Our URLs are registered in our URLconf, so they can
potentially change. By using the url tag, we can tell Django to retrieve
the appropriate URL from the URLconf rather than hard-coding in a
path.

The url tag looks for the name of the path, shelter_detail in our case,
and then the list of any expected parameters. shelter_detail has one
parameter, pk. That's the primary key, or ID, of the shelter. We specify
the ID by using shelter.id.

Create the shelter detail template

With our list template created, we can now create the detail template.

1. In dog_shelters/templates, create a new file


called shelter_detail.html.

2. Add the following code to create the template:

HTMLCopy
{% extends 'base.html' %}

{% block title %}
Shelter list
{% endblock %}

{% block content %}
<h2>{{ shelter.name }}</h2>
<div>Located in {{ shelter.location }}</div>
{% if shelter.dog_set.all %}
<div>Here is the list of available dogs</div>
{% for dog in shelter.dog_set.all %}
<div>
<a href="">
{{dog.name}}
</a>
</div>
{% endfor %}
</div>
{% else %}
<div>This shelter has no dogs available for adoption</div>
{% endif %}
{% endblock %}

Notice that in the body, we check to see if any dogs are inside the
shelter by using if shelter.dog_set.all. If there are dogs, we display
the list by using for to loop through all the dogs. Otherwise, we display
a message that says no dogs are available. We'll update the link in a
later unit.

Note

You might notice that we're making two calls to shelter.dog_set.all. If


you're experienced with databases and ORMs, you might be concerned
that we're making two calls to the database. Two calls would normally
be a performance hit. Django has built-in caching, which will ensure
that only one call to the database is made.

Test the site

With our templates created, we can see our site in action!

1. Save all files.

2. Open your browser and go to http://localhost:8000.

3. The list of shelters should now appear.


1. Select Contoso.

2. The list of dogs for the Contoso shelter now appears.

Exercise - Set up the starter


project
Completed100 XP
 2 minutes

In this module, we'll work on a website for dog shelters. This project
focuses on collecting information on all existing dog shelters and the
dogs they hope to place across the United States. The fictional hope for
this app is that dogs could find suitable homes faster because they
would have individuals looking to adopt them from around the United
States and not just their local area.

Django is the perfect framework for this project. It provides a route for
quickly developing a customer-facing app. Django also provides an
established database and admin function that could easily be accessed
by employees for quick updating. We've created the initial setup for
this project, which allows us to focus on the concepts for this module.
Requirements

You'll need the following resources installed on your computer to


complete the exercises:

 Python
 Git
 A code editor such as Visual Studio Code

Clone the starter repository

1. Open a command or terminal window.

2. Run the following commands to clone the starter repository and


change directory to the project.

BashCopy
git clone https://github.com/MicrosoftDocs/ms-learn-django-generic-
views.git
cd ms-learn-django-generic-views/starter
Note

The solution for the exercises can be found in


the solution directory.

Open the project in Visual Studio Code

We'll use Visual Studio Code as our code editor.

In the same command or terminal window, enter the following


command to open the folder in Visual Studio Code.

BashCopy
code .

Create the virtual environment

We'll follow the best practice of working with virtual environments for
our project.

1. Inside Visual Studio Code, open the terminal window by


selecting View > terminal.
2. In the new terminal window, run the following commands to
create and activate a virtual environment.

BashCopy
# Windows
py -3 -m venv venv
.\\venv\\Scripts\\activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate

Install Django

The starter project uses a requirements.txt file to contain the list of all
necessary packages. We can install them by using pip.

In the same terminal window, run the following command to install


the required packages.

BashCopy
pip install -r requirements.txt

Start the server

Django can host the application locally. We'll do this step by using the
built-in terminal window in Visual Studio Code.

Enter the following command in the same terminal window.

BashCopy
python manage.py runserver

Use generic views to display


data
Completed100 XP
 7 minutes

The generic views system in Django streamlines the creation of


repetitive code. The common operations you perform in a data-driven
application share the same pattern. For example, to display an
individual item by its ID or primary key, the workflow is always:

1. Load the item from the database by ID.


2. If the item isn't found, return a 404.
3. If the item is found, pass the item to a template for display.

The generic view system acknowledges this fact and provides classes
you can use that contain the core code already written. You inherit
from the appropriate class, set a couple of properties, and then register
an appropriate path in your URLconf. The rest is taken care of for you!

Django includes two generic views for displaying


data: DetailView and ListView.

DetailView for item detail

The generic view DetailView is used to display a detail page for an


item. DetailView retrieves the item for the specified model by the
primary key and passes it to the template. You can set template_name to
the name of the template to be used. The default
is <model>_detail.html. Finally, we can set context_object_name to the
name of the variable we want to use in our template.

To create a detail view by using the generic view for a dog, you could
use the following code:

PythonCopy
from . import models
from django.views import generic

class DogDetailView(generic.DetailView):
model = models.Dog
template_name = 'dog_detail.html'
context_object_name = 'dog'

Registering DogDetailView is similar to any other path entry. The key


thing to ensure you include is a parameter named pk. Django uses this
convention to identify the primary key. You'll also note we use
the as_view() method to convert the class into a view.

PythonCopy
path('dog/<int:pk>', views.DogDetailView.as_view(), name='dog_detail')

ListView for a list of items

The generic view ListView behaves in a similar fashion to DetailView.


You can set context_object_name for the name of the variable in the view
and template_name for the name of the template.
The primary difference is that ListView is designed to work with any
form of a query that returns multiple items. As a result, you must
override the get_queryset function. The functionget_queryset is called by
the generic view system to retrieve the items from the database, which
allows you to order or filter your items as needed.

To create a view to display the list of all shelters by using the generic
view ListView, you could use the following code:

PythonCopy
from . import models
from django.views import generic

class ShelterListView(generic.ListView):
template_name = 'shelter_list.html'
context_object_name = 'shelters'

def get_queryset(self):
return models.Shelter.objects.all()

Registering the view is performed much in the same way as


our DetailView.

PythonCopy
path('', ShelterListView.as_view(), name='shelter_list')

Exercise - Implement generic


views to display data
Completed100 XP
 2 minutes

We want to create a new detail page for dogs. We're going to use the
generic view DetailView to streamline the amount of code we need to
create.

Important

This exercise assumes that you've completed the setup steps earlier in
this module.

Create DogDetail view

We start by creating the detail view class.

1. Inside Visual Studio Code, open dog_shelters/views.py.


2. Underneath the line that reads # TODO: Import generic views, add
the following code to import the generic views module.

PythonCopy
# TODO: Import generic views
from django.views import generic

3. Add the following code to the bottom of views.py to create the


generic view for DogDetail and set the model, template, and
context object.

PythonCopy
class DogDetailView(generic.DetailView):
model = models.Dog
template_name = 'dog_detail.html'
context_object_name = 'dog'

Register the detail view

With the view created, we can register the path.

1. Open dog_shelters/urls.py.

2. Underneath the line that reads # TODO: Register detail view, add
the following code to register the path for our DogDetailView.

PythonCopy
# TODO: Register detail view
path('dog/<int:pk>', views.DogDetailView.as_view(),
name='dog_detail'),
Important

Remember the trailing comma at the end of the line.

Create the HTML template

Now you'll create the HTML template to display out the details of the
dog. The object name will be dog as we set that when creating the
form.

1. Inside Visual Studio Code, create a new file


inside dog_shelters/templates named dog_detail.html.

2. Add the following code to dog_detail.html to create the template


to display the details for the dog.
HTMLCopy
{% extends 'base.html' %}

{% block title %}
{{ dog.name }}
{% endblock %}

{% block content %}
<h2>{{ dog.name }}</h2>
<div>About {{ dog.name }} - {{ dog.description }}</div>
{% endblock %}

Update the shelter detail page to include our link

With our path registered and template created, we can update the
shelter detail template to include links to our dog detail page.

1. Open dog_shelters/templates/shelter_detail.html.

2. Underneath the line that reads {# TODO: Add link to dogs #}, add
the following code to create a link for each dog to the detail view.

HTMLCopy
{# TODO: Add link to dogs #}
<a href="{% url 'dog_detail' dog.id %}">
{{dog.name}}
</a>

Test your page

With everything created, let's see our page in action.

1. Save all the files by selecting File > Save All.

2. In your browser, go to http://localhost:8000.

3. From the list of shelters, select Contoso.

4. From the list of dogs, select Roscoe.

The details page appears.


We've now created a view by using the generic view system in Django!

Use generic views to edit data


Completed100 XP
 6 minutes

Like the code required to display data, the code to allow users to
modify data is repetitive. It can also be tedious because several steps
are required to ensure the data is valid and sent correctly. Fortunately,
the generic view system can streamline the amount of code we need to
enable this functionality.

Create new items

Before we explore how Django can streamline our development, we


should review the process that allows users to modify data. Let's
explore the workflow the server uses to manage the process of
creating a new item or piece of data, and the work that goes into
creating the HTML form.

Creation workflow

At the surface, the code to allow a user to create an item might seem
trivial. As it turns out, it's a deceptively involved process.

1. The user sends a GET request to signal they want the form to
create a new item.
2. The server sends the form with a special token to prevent cross-
site request forgery (CSRF).
3. The user completes the form and selects submit, which sends
a POST request to indicate the form has been completed.
4. The server validates the CSRF token to ensure no tampering has
taken place.
5. The server validates all information to ensure it meets the rules.
An error message is returned if validation fails.
6. The server attempts to save the item to the database. If it fails, an
error message is returned to the user.
7. After successfully saving the new item, the server redirects the
user to a success page.

This process requires quite a bit code! Most of it's boilerplate, which
means it's the same every time you create it.

Forms

Creating an HTML form can be a tedious process. Developers are often


copying and pasting input tags, looping through lists to create drop-
downs lists, and setting up radio buttons. Whenever the model
changes, the form must be updated.

You might have noticed the models we create in Django contain


everything necessary to create the form. When we added the various
fields, we indicated the data types, which are coupled with different
HTML elements. For example, a Boolean field would be a check box
and a foreign key would commonly be a drop-down list.

Generic views to modify data

One of Django's key goals is to eliminate the need to constantly re-


create the same blocks of code over and over. To support this goal for
data modifications, Django provides a collection of generic classes and
forms to manage this workload for us. As we'll see, it includes all the
necessary code and can even create the form for us dynamically. The
classes used for creating, updating, and deleting data are
called CreateView, UpdateView, and DeleteView.

CreateView

The class CreateView is used to allow a user to create items. It walks


through the preceding process and dynamically creates the form. After
success, it displays the detail page for the newly created item.

You specify the model and template_name you want to associate with it
just as you would with the other generic views. The key difference
for CreateView is the inclusion of a fields property where you list the
editable fields. By using this property, you can ensure fields that
shouldn't be edited, like a creation date, don't appear on the form. The
view to create a new dog might look like the following sample:

PythonCopy
from . import models
from django.views import generic

class DogCreateView(generic.CreateView):
model = models.Dog
template_name = 'dog_form.html'
fields = ['name', 'description', 'shelter']

UpdateView

The class UpdateView behaves in an identical fashion to CreateView. The


only difference is that it automatically loads an item based on
the pk parameter. Django uses this convention for the primary key for
an item.

PythonCopy
from . import models
from django.views import generic

class DogUpdateView(generic.CreateView):
model = models.Dog
template_name = 'dog_form.html'
fields = ['name', 'description', 'shelter']

After successfully creating or updating an item, Django redirects to the


details page for the item. It retrieves the URL for the details by
using get_absolute_url on the associated model. You implement this
method by returning the correct URL. You can retrieve the appropriate
URL from URLconf by using reverse. Note kwargs is used to pass
the pk or primary key parameter to the route.

PythonCopy
from django.db import models
# TODO: Import reverse
from django.urls import reverse
class Dog(models.Model):
# Existing code
def get_absolute_url(self):
return reverse('dog_detail', kwargs={"pk": self.pk})
DeleteView

The class DeleteView is similar to UpdateView. It allows a user to delete an


item and identifies the item to be deleted by using pk.
Unlike UpdateView, fields isn't needed because you'll be deleting the
entire item. Also, because no item has been newly created or updated,
we need to determine where we want to redirect the user. We can
create a redirect by setting the success_url to the appropriate value.
You can look up a URL by using reverse_lazy.

PythonCopy
from . import models
from django.views import generic
from django.urls import reverse_lazy

class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('author-list')
Note

We use reverse_lazy because of the order in which information is


loaded into Django.

Form templates for create and update

The generic views can create the HTML form for us dynamically. All we
need to provide is a template to act as the placeholder for the form.
The placeholder template ensures the form matches the rest of our
site. Fortunately, we don't need much code to create it.

The generic views automatically create a form variable for our template
to use. The form elements provided by Django can be displayed
inside <p> tags or as a <table>.

The form variable contains all of the appropriate HTML to create the
controls from the form. It doesn't contain the <form> tag itself or
a submit button. Our template must include four items:

 The form element with the method set to POST because this setting
triggers the save operation on the server.
 The code {% csrf_token %} to add the CSRF token to prevent
spoofing.
 The code {{ form.as_p }} or {{ form.as_table }} to display the
dynamically generated form.
 The submit button.

The following code can act as the host for any generic view form.
HTMLCopy
<form method="post">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>

Exercise - Implement generic


views to edit data
Completed100 XP
 2 minutes

To allow users to register new dogs at a shelter, we'll use CreateView.

Update the model to support get_absolute_url

Let's start by updating the model to support get_absolute_url.

1. Inside Visual Studio Code, open dog_shelters/models.py.

2. Add the following code underneath the line that reads # TODO:
Import reverse to import the reverse function.

PythonCopy
# TODO: Import reverse
from django.urls import reverse

3. Add the following code to the Dog class immediately the line that
reads # TODO: Add get_absolute_url to read the dog_detail path
from URLconf and pass the ID as the parameter.

PythonCopy
# TODO: Add get_absolute_url
def get_absolute_url(self):
return reverse('dog_detail', kwargs={"pk": self.pk})
Important

Remember Python manages enclosures with tabs rather than braces ( {


}). Because of this fact, get_absolute_url needs to at the same tab level
as the #TODO comment. You can refer to the files in
the solution directory to see the completed project.

Create DogCreateView

Let's create DogCreateView to allow someone to register a dog.


1. Inside Visual Studio Code, open dog_shelters/views.py.

2. At the end of views.py, add the following code to


create DogCreateView.

PythonCopy
class DogCreateView(generic.CreateView):
model = models.Dog
template_name = 'dog_form.html'
fields = ['shelter', 'name', 'description']

We set the model to be Dog, our template to be dog_form.html, and


the list of fields we want to be editable.

Note

The order in which you list the fields will be the order that they'll be
displayed in the form.

Register the route

With our view created, let's register the route in our URLconf.

1. Inside Visual Studio Code, open dog_shelters/urls.py.

2. Underneath the line that reads # TODO: Register create view, add
the following code to register the route.

PythonCopy
# TODO: Register create view
path('dog/register', views.DogCreateView.as_view(),
name='dog_register'),

Create the HTML template

Let's create the template to host our form.

1. Inside Visual Studio Code, create a new file


inside dog_shelters/templates named dog_form.html.

2. Add the following code to dog_form.html to create the template


to host our form.

HTMLCopy
{% extends 'base.html' %}
{# TODO: Register crispy_forms_tags #}

{% block title %}
Register dog at shelter
{% endblock %}

{% block content %}
<h2>Register dog at shelter</h2>
<form method="POST">
{% csrf_token %}

{{ form.as_p }}

<button type="submit" class="btn btn-primary">Save</button>


</form>
{% endblock %}
Note

We're adding a note for ourselves to add a library, which we'll do in the
next exercise.

Create a link to the registration page

Let's create a link on our shelter list page, which is currently the home
page for our application, to the register page we created.

1. Inside Visual Studio Code,


open dog_shelters/templates/shelter_list.html.

2. Underneath the line that reads {# TODO: Add link to registration


page #}, add the following code to create the link.

HTMLCopy
{# TODO: Add link to registration page #}
<div>
<a href="{% url 'dog_register' %}">Register a dog available for
adoption</a>
</div>

Test the page

Let's see our page in action.

1. Save all files by selecting File > Save All.

2. In your browser, go to http://localhost:8000.

3. Select Register a dog available for adoption.


You should now see the form.

1. Notice how our foreign key relationship becomes a drop-down list.

2. Choose a shelter, and add a name and description for a dog.

3. Select Save.

You're now redirected to the details page for your dog!

You've now created a creation form by using CreateView in Django.

Exercise - Implement django-


crispy-forms
Completed100 XP
 7 minutes
After you view the created form, you might notice that the formatting
isn't the same as the rest of our page. We're using Bootstrap, and the
form currently isn't. Fortunately, there's a library that can ensure our
forms use Bootstrap too.

The django-crispy-forms library

The django-crispy-forms library further enhances how forms are


generated by Django. We're going to explore how we can use the
library to ensure our forms use Bootstrap.

Install the library

As with any Python library, we install django-crispy-forms by


using pip.

1. Inside Visual Studio Code, open requirements.txt.

2. At the bottom of the file, add a new line that reads:

textCopy
django-crispy-forms

3. Open a new terminal window by selecting Terminal > New


Terminal.

4. Install all packages by running the following command:

BashCopy
pip install -r requirements.txt

Register the app in Django and configure the


template

Anything Django uses must be registered as an app or middleware.


Because django-crispy-forms is an app, we'll list it in
the INSTALLED_APPS list.

1. Inside Visual Studio Code, open project/settings.py.

2. Underneath the line that reads # TODO: Register crispy_forms, add


the following code to register django-crispy-forms.
PythonCopy
# TODO: Register crispy_forms
'crispy_forms',

3. Underneath the line that reads # TODO: Set template_pack, add the
following code to configure django-crispy-forms to use Bootstrap
4.

PythonCopy
# TODO: Set template_pack
CRISPY_TEMPLATE_PACK = 'bootstrap4'

Update our template to use django-crispy-forms

The bulk of the amazing work that django-crispy-forms does is by using


a filter. A filter allows you to take a variable in a template and pass it
into another handler or process. In our case, the crispy filter will
convert our form to the specified template, Bootstrap 4.

1. Inside Visual Studio Code,


open dog_shelters/templates/dog_form.html.

2. Underneath the line that reads {# TODO: Load crispy_forms_tags #},


add the following code to load the filter or tag.

HTMLCopy
{# TODO: Load crispy_forms_tags #}
{% load crispy_forms_tags %}

3. Replace the line that reads {{ form.as_p }} with the following code
to use the crispy filter.

HTMLCopy
{{ form | crispy }}

Test the site

With everything installed and updated, let's test our site.

1. Save all files by selecting File > Save All.

2. In your browser, go to http://localhost:8000/dog/register.

You'll see the page is now using Bootstrap for the form.
You've now updated your application so that the form uses Bootstrap.

Get the starter


Completed100 XP
 2 minutes

In this module, you'll work on a website for dog shelters. This project
collects information about all dog shelters and their adoption-ready
dogs across the country/region. The fictional goal of this app is to find
suitable homes for the dogs quickly. The app reaches individuals who
want to adopt, not just in the shelters' local areas but across the
country/region.

Django is the perfect framework for this project. It allows you to quickly
develop a customer-facing app. It also provides an established
database and admin function that shelter employees can easily update.
We've created the initial setup for this project so you can focus on the
concepts for this module.

Requirements

To complete the exercise, you need the following tools installed on


your computer:

 Python
 Git
 A code editor such as Visual Studio Code

Clone the starter repository

1. Open a command window or terminal.

2. Run the following commands to clone the starter repository and


change to the project's directory.

BashCopy
git clone https://github.com/MicrosoftDocs/mslearn-django-deployment
cd mslearn-django-deployment/starter
Note

The solution for the exercises can be found in


the solution directory.

Open the project in Visual Studio Code

You'll use Visual Studio Code as your code editor.

BashCopy
code .

Create the virtual environment

You'll follow the best practice of working with virtual environments for
this project:

1. In Visual Studio Code, open the terminal by


selecting View > Terminal.
2. In the Terminal pane, run the following commands to create and
activate a virtual environment.

BashCopy
# Windows
py -3 -m venv venv
.\\venv\\Scripts\\activate

# macOS or Linux
python3 -m venv venv
source ./venv/bin/activate

Install Django

The starter project uses a requirements.txt file to contain the list of all
necessary packages. You can install them by using pip.

In the Terminal pane, run the following command to install the


required packages.

BashCopy
pip install -r requirements.txt

Start the server

Django can host the application locally. Set up the hosting from the
terminal pane.

Enter the following command in the Terminal pane.

BashCopy
python manage.py runserver

Introduction
Completed100 XP
 5 minutes

Creating a web application with artificial intelligence (AI) doesn't need


to involve a lot of code or creating services from scratch. Let's imagine
we wanted to create a website that can translate text for the user.

For the front end, we want something that will allow us to integrate our
services without having to jump through a lot of hoops. A framework
like Flask is a perfect choice. Flask is described by its creators as a
"micro-framework", meaning it provides the core services required,
such as routing and templating, but otherwise allows you to use
whatever backend services your application needs. It's also
lightweight, making it quick to set up and deploy. We don't need a
database or anything fancy. We just need a framework to create our UI,
and be able to call the back-end service.

For the back end, rather than creating a machine learning model on
your own, you can use a collection of AI services (known as Azure
Cognitive Service). These services can either be accessed via an SDK
or an HTTP call. We can use the Translator service to meet our primary
goal of translating text.

In this module, we're going to explore Flask and the Translator service.
We'll see how we can create a web application to translate text into
various languages.

Learning objectives

In this module, you'll build a website using Flask and Azure AI services
to translate text.

 Learn how to set up a Flask development environment


 Learn how to use Flask to build a form
 Learn how to use the Translator service to translate text

Prerequisites

 An Azure account. Create Your Azure Free Account.


 Visual Studio Code installed on your computer. Download Visual
Studio Code
 Python 3.6 or later installed on your computer. Instructions for
installing Python
 The Python extension for Visual Studio Code installed on your
computer. Python extension for Visual Studio Code

Exercise - Set up a development


environment
Completed100 XP
 15 minutes

To get started writing our Flask application with Python, we need to set
up our development environment, which will require a couple of items
to be installed. Fortunately, the tools we'll use are relatively common,
so they'll serve you well even beyond this module. You might even
have them installed! We'll use these tools to develop and test your
application locally.

In this unit, you'll learn how to install Python tooling and create a
virtual Python environment. You'll install Flask, which is the framework
we'll use for creating the website.

Important

In this module, you install and configure a variety of software packages


and create a Python virtual environment. After the virtual environment
is activated in your Command Prompt window or terminal, keep the
window or terminal open. If you close your window or terminal, be sure
to restart your same Python virtual environment in the new window or
terminal. It's important to do all of your work in the same Python virtual
environment that you create at the beginning of this module.

At a high level, we'll perform the following steps:

1. Install Visual Studio Code (if not already installed)


2. Install Python (if not already installed)
3. Create a directory for your code
4. Create a virtual environment
5. Install Flask and other libraries

Install Visual Studio Code

Visual Studio Code is an open-source code editor that allows you to


create almost any type of application you might like. It's backed by a
robust extension marketplace where you can find add-ons to help
make your life as a developer easier.

 Download Visual Studio Code

Install Python

To complete this unit, you must have Python 3.6 or later installed on
your computer. There's a chance you might already have Python
installed, especially if you've already used it. You can confirm whether
it's installed by executing one of the following commands:

BashCopy
python --version
If Python is installed, the output shows the Python version number. If
you need to install Python, follow the steps in the Install a Python
interpreter documentation for Visual Studio Code. You will also need to
install the Visual Studio Code Python extension.

Important

If you're using Windows, make sure that the folder location where you
installed Python is added to your PATH environment variable. If you
miss this step you'll receive an error message "Python isn't found",
even after performing the installation. To fix this, you would need to
follow these steps to add python to your PATH environment variable:

1. Find the directory with your python.exe file. You can type python
where in the command prompt terminal to locate the python.exe
file
2. Copy the path value "C:\<python path>", you will add it to
the Path variable in step 6
3. Click the Start menu and type Edit the system environment
variables, which opens up a System Properties window.
4. Under the Advanced tab, click on the Environment
Variables button.
5. Under the user variables, double click on the variable called Path,
which will pop up a window with a list of paths
6. Click New and paste in the copied path.
7. Once inserted, click Ok and Python should now be reachable from
any location in your computer
Note

To verify the path configuration was successful, open a new command


prompt terminal and type python to see the python version info. In
case you are unable to still run a python command, restart your
computer for the changes to be effected.

Create the project directory

Create a directory in the location of your choice. This directory will be


your project directory, and will contain all of the code we'll create.
You can create a directory from a command or terminal window with
one of the following commands:

BashCopy
# Windows, macOS or Linux
mkdir contoso
cd contoso
Important
Keep your command or terminal window open for the entirety of the
module.

Create a Python virtual environment

A Python virtual environment isn't necessarily as complex as it sounds.


Rather than creating a virtual machine or container, a virtual
environment is a folder that contains all of the libraries we need to run
our application, including the Python runtime itself. By using a virtual
environment, we make our applications modular, allowing us to keep
them separate from one another and avoid versioning issues. As a best
practice you should always use virtual environments when working
with Python.

To use a virtual environment, we'll create and activate it. We create it


by using the venv module, which you installed as part of your Python
installation instructions earlier. When we activate it, we tell our system
to use the folder we created for all of its Python needs.

BashCopy
# Windows, macOS or Linux
# Create the environment
python -m venv venv

The process of creating a virtual environment may take a few seconds.


Wait for the terminal prompt to appear again before activating the
environment.

BashCopy
# Windows
# Activate the environment
./venv/scripts/activate

# macOS or Linux
# Activate the environment
source ./venv/bin/activate

Install Flask and other libraries

With our virtual environment created and activated, we can now install
Flask, the library we need for our website. We'll install Flask by
following a common convention, which is to create
a requirements.txt file. The requirements.txt file isn't special in
and of itself; it's a text file where we list the libraries required for our
application. But it's the convention typically used by developers, and
makes it easier to manage applications where numerous libraries are
dependencies.

During later exercises, we'll use a couple of other libraries,


including requests (to call Translator service) and python-dotenv (to
manage our keys). While we don't need them yet, we're going to make
our lives a little easier by installing them now.

1. In the command or terminal window, run the following command


to open the directory in Visual Studio Code:

BashCopy
code .

2. In Visual Studio Code, in the Explorer window, select New


File next to the contoso directory

1. Name the file requirements.txt, and add the following text:

textCopy
flask
python-dotenv
requests

2. Save the file by clicking Ctrl-S, or Cmd-S on a Mac


3. Return to the command or terminal window and perform the
installation by using pip to run the following command:

BashCopy
pip install -r requirements.txt

The command downloads the necessary libraries and their


dependencies.

Note
You may receive an error message if your version of pip is not the
most recent. Follow the instructions on the error message to perform
the upgrade. The upgrade isn't required for this module.

Congratulations! You've now setup your environment for development!

Flask fundamentals
Completed200 XP
 10 minutes

Flask is an open-source web "micro-framework". When the creators use


the term "micro-framework", they mean that the framework will
perform the required tasks of a web framework, but that it doesn't
include advanced features, or other specific requirements that your
application must follow to work correctly. This approach allows Flask to
be extremely flexible, and perfect for use as a front end to existing
back ends or APIs - like Azure AI services!

When creating a web application with any framework, there are a


couple of core concepts we need to understand - routing, methods, and
templating. Let's explore these concepts before we write our code.

Responding to user requests with routes

When a user uses a web application, they indicate what they want to
do, or the information they're seeking, by browsing to different uniform
resource locators (or URLs). They might type out an address directly
(say https://adventure-works.com), or select a link, or a button that
includes the appropriate URL. On an e-commerce site you might have
URLs that look like the following:

 https://adventure-works.com/ for the main page


 https://adventure-works.com/products/widget for details on a Widget
 https://adventure-works.com/cart/buy to complete a purchase

As a developer, we actually don't need to worry about the first part of


the URL, or the domain (adventure-works.com in our example). Our
application is put into action based on whatever comes after the
domain name, starting with the /. The portion after the domain name is
what's known as a route.

A route is a path to an action. Similar to tapping on a button in a


mobile app, a route indicates the action the user wants to perform.
We'll register different routes in our web application to respond to the
various requests our application supports.
In our application, we indicate how we want to respond to a particular
route request by providing a function. A route is a map to a function.
When we think about writing code in general, this concept is relatively
natural. When we want to perform a particular action, we call a
function. Our users will do the exact same thing! They'll just do it a
little differently, by accessing a route.

Methods or verbs

Routes can be accessed in many ways, through what are known as


methods or verbs (the two terms mean the same thing and can be
used interchangeably). How the route is accessed provides additional
context about the state of the user request and what action the user
wants to perform.

There are many methods available when creating a web application,


but the two most common (and the only two we'll focus on)
are GET and POST. GET typically indicates that the user is requesting
information, while POST indicates that the user needs to send us
something and receive a response.

Note

Regardless of the verb used, information can always be returned to


the user.

A common application flow that uses GET and POST revolves around
using a form. Let's say we create an application where the user wants
to register for a mailing list:

1. The user accesses the sign-up form via GET


2. The user completes the form and selects the submit button
3. The information from the form is sent back to the server by
using POST
4. A "success" message is returned to the user

As you might suspect, the user doesn't directly indicate the verb they
want to use, it is controlled by the application. Generally speaking, if
the user navigates to a URL directly, by typing it in or by selecting a
link, they access the page by using GET. When they select a button for
a form, they typically send the information via POST.

Note

We're keeping this conversation relatively high level, because a full


discussion of methods is beyond the scope of this module.
Templates

Hypertext Markup Language, or HTML, is the language used to


structure the information displayed on a browser, while Cascading
Style Sheets, or CSS, is used to manage the style and layout. When
creating an application, most of the HTML will be static, meaning it
won't change. However, to make our pages dynamic we need to be
able to programmatically put information into an HTML page. Nearly
every web framework supports this requirement through templates.

A template allows you to write the core HTML (or a template) and
indicate placeholders for the dynamic information. Probably the most
common syntax for placeholders is {{ }}. Jinja, the templating engine
for Flask, uses this syntax.

HTMLCopy
<h1>Welcome, {{ name }}</h1>

In the preceding example, we have our HTML of h1 (a header), with the


text we want to display. The {{ name }} indicates that we want to
display a variable named name right after Welcome. By using this
syntax we can write our HTML with our existing skills, and inject the
dynamic information as needed.

Exercise - Create an app


Completed200 XP
 10 minutes

We're going to create our application iteratively, focusing on specific


concepts as we go. To start, we'll create the landing page for our
application, which will display the form the user will use.

Typically, the entry point for Flask applications is a file named app.py.
We're going to follow this convention and create the core of our
application. We'll perform the following steps:

1. Create our core application


2. Add the route for our application
3. Create the HTML template for our site
4. Test the application
Create core application

1. Returning to the instance of Visual Studio Code we were using


previously, create a new file named app.py by clicking New
file in the Explorer tab

Exercise - Create an app


Completed200 XP
 10 minutes

We're going to create our application iteratively, focusing on specific


concepts as we go. To start, we'll create the landing page for our
application, which will display the form the user will use.

Typically, the entry point for Flask applications is a file named app.py.
We're going to follow this convention and create the core of our
application. We'll perform the following steps:

1. Create our core application


2. Add the route for our application
3. Create the HTML template for our site
4. Test the application

Create core application

1. Returning to the instance of Visual Studio Code we were using


previously, create a new file named app.py by clicking New
file in the Explorer tab

1. If this exercise is your first time using Visual Studio Code to create
a Python application, you'll receive messages about installing the
Python extension and the linter pylint. Select Install to install
each of these add-ons.

2. Add the code to create your Flask application

PythonCopy
from flask import Flask, redirect, url_for, request, render_template,
session

app = Flask(__name__)

The import statement includes references to Flask, which is the core of


any Flask application. We'll use render_template in a while, when we
want to return our HTML.

app will be our core application. We'll use it when we register our routes
in the next step.

Add the route

Our application will use one route - /. This route is sometimes called
either the default or the index route, because it's the one that will be
used if the user doesn't provide anything beyond the name of the
domain or server.

Add the following code to the end of app.py

PythonCopy
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')

By using @app.route, we indicate the route we want to create. The path


will be /, which is the default route. We indicate this will be used
for GET. If a GET request comes in for /, Flask will automatically call
the function declared immediately below the decorator, index in our
case. In the body of index, we indicate that we'll return an HTML
template named index.html to the user.

Create the HTML template for our form

Jinja, the templating engine for Flask, focuses quite heavily on HTML.
As a result, we can use all the existing HTML skills and tools we already
have. We're going to use Bootstrap to lay out our page, to make it a
little prettier. By using Bootstrap, we'll use different CSS classes on our
HTML. If you're not familiar with Bootstrap, you can ignore the classes
and focus on the HTML (which is really the important part).

Important

HTML (Hypertext Markup Language) is a standard markup language


used to create web pages. HTML consists of a series of tags and
attributes to create headings, paragraphs, lists, images, links, and
other elements that make up a web page. When a user requests a web
page, their browser reads the HTML code and renders it as a visual web
page that the user can interact with. To learn more about HTML,
see HTML basics.

Templates for Flask need to be created in a folder named templates,


which is fitting. Let's create the folder, the necessary file, and add the
HTML.

1. Create a new folder named templates by selecting New


Folder in the Explorer tool in Visual Studio Code

2. Select the templates folder you created, and select New File to
add a file to the folder

3. Name the file index.html

4. Add the following HTML

HTMLCopy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.
min.css" rel="stylesheet" integrity="sha384-
9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous">
<title>Translator</title>
</head>
<body>
<div class="container">
<h1>Translation service</h1>
<div>Enter the text you wish to translate, choose the
language, and click Translate!</div>
<div>
<form method="POST">
<div class="form-group">
<textarea name="text" cols="20" rows="10"
class="form-control"></textarea>
</div>
<div class="form-group">
<label for="language">Language:</label>
<select name="language" class="form-control">
<option value="en">English</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="ru">Russian</option>
<option value="de">German</option>
</select>
</div>
<div>
<button type="submit" class="btn btn-
success">Translate!</button>
</div>
</form>
</div>
</div>
</body>
</html>

The core components in the HTML above are the textarea for the text
the user wishes to translate, and the dropdown list ( select), which the
user will use to indicate the target language. If you want to add more
languages, you can consult the list of supported languages for other
options. Set the value attribute to the language code, for
example, pl for Polish.

Test the application

With our initial site created, it's time to test it! We're going to use the
integrated terminal inside Visual Studio Code to make our lives a little
easier.

1. Open the integrated terminal by selecting Ctrl-` or Cmd-` on a


Mac

2. Run the following command to set the Flask runtime to


development, which means that the server will automatically
reload with every change

BashCopy
# Windows
set FLASK_ENV=development

# Linux/macOS
export FLASK_ENV=development

3. Run the application!

BashCopy
flask run

4. Open the application in a browser by navigating


to http://localhost:5000

You should see the form displayed! Congratulations!

Translation
100 XP
 10 minutes

While solutions using machine learning or artificial intelligence have


become increasingly common, they can still be difficult to create from
scratch. Fortunately, there are many solutions already built, which we
can access like we would any application programming interface (API).
This approach allows us to focus on our code, rather than complex
modeling.

Azure provides a set of offerings called Azure AI services, which include


services for computer vision, speech to text and text to speech, and
text translation. You can access any of these services via software
developer kits (SDKs), or by calling them in the same way you'd call
any other HTTP endpoint.

To use Azure AI services, you'll need an Azure account. If you're new to


Azure, you can sign-up for free, which will include $200 free credit for
the first 30 days. If you're a student, you can enroll for Azure for
Students, which includes $100 to use across 12 months, and a host of
other free services.

Translator service

Translator service, part of Azure AI services, will translate to and from


dozens of languages. It can automatically detect the source language,
and can translate to multiple target languages in one call. You call
Translator service in the same way you would call any other HTTP
endpoint. In Python, you typically do this by using
the requests library, which is what we'll use when we return to our
code.

Key management

To call Translator service (or any other Cognitive Service), we'll need a
key. This key will be used whenever we access the service. The key is
similar to a password. Anyone who has access to the key can call the
service, and if we were using a paid version they could run up a large
bill!

One great solution for protecting the key when doing development
work is to use a library called python-dotenv, commonly called dotenv.
When using dotenv, we create a file named .env, which contains
any key/value pairs we don't want as part of our source code. We'll
ensure that the file is listed in our gitignore file when we push our code
to GitHub, so that we don't accidentally publish it for the world to see.

You might also like