Django For Beginners Build Websites With Python Django download
Django For Beginners Build Websites With Python Django download
Django download
https://ebookbell.com/product/django-for-beginners-build-
websites-with-python-django-43712546
https://ebookbell.com/product/django-for-beginners-build-websites-
with-python-django-40-william-s-vincent-43812410
Django For Beginners Build Websites With Python And Django 1st Edition
William S Vincent
https://ebookbell.com/product/django-for-beginners-build-websites-
with-python-and-django-1st-edition-william-s-vincent-11043734
Django For Beginners Build Websites With Python And Django Welcome To
Django Book 1 William S Vincent
https://ebookbell.com/product/django-for-beginners-build-websites-
with-python-and-django-welcome-to-django-book-1-william-s-
vincent-49182952
Django For Beginners Build Websites With Python And Django 21 William
S Vincent
https://ebookbell.com/product/django-for-beginners-build-websites-
with-python-and-django-21-william-s-vincent-7415256
Django For Beginners Build Websites With Python And Django Vincent
https://ebookbell.com/product/django-for-beginners-build-websites-
with-python-and-django-vincent-12036592
https://ebookbell.com/product/django-for-beginners-31-31-william-s-
vincent-22471298
https://ebookbell.com/product/django-for-beginners-william-s-
vincent-56458436
https://ebookbell.com/product/django-for-beginners-converted-william-
s-vincent-56537090
https://ebookbell.com/product/django-for-beginners-william-s-
vincent-44609942
Django for Beginners
William S. Vincent
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have the right book and build
traction once you do.
Introduction 1
Why Django 1
Why This Book 2
Prerequisites 3
Book Structure 3
Book Layout 4
Advice on Getting Stuck 5
Community 6
Conclusion 6
Heroku Deployment 90
Conclusion 91
SendGrid 213
Custom Emails 220
Conclusion 222
DATABASES 285
Static Files 287
Deployment Checklist 289
GitHub 291
Heroku Deployment 291
Conclusion 294
Conclusion 295
Next Steps 295
3rd Party Packages 296
Learning Resources 296
Python Books 297
Feedback 297
Introduction
Welcome to Django for Beginners, a project-based approach to learning web development with
the Django1 web framework. In this book you will build five progressively more complex web
applications, starting with a simple Hello, World app, progressing to a Pages app, a Message Board
app, a Blog app with forms and user accounts, and finally a Newspaper app that uses a custom
user model, email integration, foreign keys, authorization, permissions, and more. By the end
of this book you should feel confident creating your own Django projects from scratch using
current best practices.
Django is a free, open source web framework written in the Python programming language. First
released in 2005, Django has been in continuous development since then and today powers many
of the largest websites in the world including Instagram, Pinterest, Bitbucket, and Disqus. At the
same time, it is flexible enough to be a popular choice for early-stage startups and side projects.
Why Django
A “web framework” is a collection of tools that abstract away much of the difficulty–and
repetition–inherent in web development. For example, most websites need the same basic
functionality: the ability to connect to a database, set URL routes, display content on a page,
handle security properly, and so on. Rather than recreate all of this from scratch, programmers
over the years have created web frameworks in all the major programming languages: Django in
Python, Rails in Ruby, and Laravel in PHP among many, many others.
Django inherited Python’s “batteries-included” approach and includes out-of-the box support
for common tasks in web development, including:
• user authentication
• testing
1
https://djangoproject.com
Introduction 2
This approach allows web developers to focus on what makes a web application unique rather
than reinventing the wheel every time.
In contrast, some web frameworks like Flask2 adopt a microframework approach of providing only
the bare minimum required for a simple web page. Flask is far more lightweight than Django and
allows for maximum flexibility, however this comes at a cost to the developer. To build even a
basic website requires adding a dozen or more third-party packages, which may or may not be
up-to-date. And the resulting Flask project structure often varies widely, making it more difficult
to move between projects and maintain best practices within the community.
Django remains under active development3 with a regular release schedule of monthly securi-
ty/bug fixes and a major new release every 8 months. Millions of programmers have already used
Django to build their websites. It doesn’t make sense to repeat the same code–and mistakes–
when a large community of brilliant developers has already solved these problems for us.
The Django community is also constantly adding new features and security improvements.
And best of all, it’s written in the wonderfully readable yet still powerful Python programming
language. In short, if you’re building a website from scratch Django is a fantastic choice.
I wrote this book because while Django is extremely well documented there is a severe lack of
beginner-friendly tutorials available. When I first learned Django years ago, I struggled to even
complete the official polls tutorial4 . Why was this so hard I remember thinking?
With more experience, I now recognize that the writers of the Django docs faced a difficult
choice: they could emphasize Django’s ease-of-use or its depth, but not both. They choose the
2
https://flask.palletsprojects.com/en/2.0.x/
3
https://www.djangoproject.com/download/#supported-versions
4
https://docs.djangoproject.com/en/4.0/intro/tutorial01/
Introduction 3
latter and as a professional developer I appreciate the choice, but as a beginner I found it so…
frustrating! My goal with this book is to fill in the gaps and showcase how beginner-friendly
Django really can be.
Prerequisites
Django for Beginners is written for Django 4.0 and Python 3.10. All the code examples work with
these versions. By the time you read this, there may be newer versions of both Django and Python
available. In general, you should always strive to be on the latest version of Django and Python.
As both are mature technologies, any issues that arise in the future as a result will be relatively
minor.
You don’t need previous Python or web development experience to complete this book. It is
intentionally written so that even a total beginner can follow along and feel the magic of writing
their own web applications from scratch. However, if you are serious about a career in web
development, you will eventually need to invest the time to properly learn Python, HTML, and
CSS. A list of recommended resources for further study is included in the Conclusion.
Book Structure
The book begins by demonstrating how to configure a local development environment for both
Windows and macOS in Chapter 1. The command line is covered in depth along with Git, text
editors, and proper installation of Python and Django.
In Chapter 2 we build our first project, a minimal Hello, World app that demonstrates how to set
up new Django projects. Because establishing good software practices is important, we’ll also
save our work with Git and upload a copy to a remote code repository on GitHub.
In Chapter 3 we make, test, and deploy a Pages app that introduces templates and class-based
views. Templates are how Django allows for DRY (Don’t Repeat Yourself) development with HTML
and CSS while class-based views are quite powerful yet require a minimal amount of code. We
also add our first tests and deploy to Heroku’s free tier. Using platform-as-a-service providers
like Heroku transforms deployment from a painful, time-consuming process into something that
Introduction 4
In Chapter 4 we build our first database-backed project which is a Message Board app. Django
provides a powerful ORM (Object-Relational-Mapper) that translates our Python code into the
necessary SQL for multiple different backends. We’ll explore the built-in admin app which
provides a graphical way to interact with our data and can be even used as a CMS (Content
Management System) similar to Wordpress. Of course, we also write tests for all our code, store
a remote copy on GitHub, and deploy to Heroku.
In Chapters 5-7 we’re ready for a Blog app that implements CRUD (Create-Read-Update-Delete)
functionality. By using Django’s generic class-based views we only have to write only a small
amount of actual code for this. Then we’ll add forms and integrate Django’s built-in user
authentication system for sign up, log in, and log out functionality.
The remainder of the book, Chapters 8-16, is dedicated to building a robust Newspaper site,
starting with the introduction to custom user models in Chapter 8, a Django best practice that
is rarely addressed in tutorials. Chapter 9 covers user authentication, Chapter 10 adds Bootstrap
for styling, and Chapters 11-12 implement password reset and change via email. With Chapters
13-15 we add articles and comments along with proper permissions and authorizations. We even
learn some tricks for customizing the admin to display our growing data.
Chapter 16 covers production-ready deployment through the use of environment variables and
several additional packages. And the Conclusion provides an overview of the major concepts
introduced in the book and a list of recommended resources for further learning.
The book’s structure is very deliberate: each chapter introduces a new concept and reinforces
past teachings. I highly recommend reading the book in order, even if you’re eager to skip ahead.
Later chapters won’t cover previous material in the same depth as earlier chapters.
By the end of this book you’ll have a solid understanding of how Django works, the ability to build
apps on your own, and the background needed to fully take advantage of additional resources
for learning intermediate and advanced Django techniques.
Book Layout
There are many code examples in this book, which are denoted as follows:
Introduction 5
Code
For brevity we will use three dots, ..., to denote existing code that remains unchanged in a
longer code example. For example, in the function below, the previous content is unchanged
and the print() statement has been added. In these cases there will also be a comment, # new,
indicating where the new code has been added.
Code
def make_my_website:
...
print("All done!") # new
Getting stuck on an issue is part of being a programmer. It happens to everyone at every level.
The only thing that changes is the difficulty of the question being tackled. Part of learning how
to be a better developer is accepting this frustration and learning how to find help, ask targeted
questions, and determine when you need to take a walk around the block to clear your head
versus being truly stuck on something.
The good news is that whatever error you are having, it is likely that you are not the first!
Copy and pasting your error into a search engine like Google or DuckDuckGo will typically
bring up something from StackOverflow or a personal blog detailing the exact same issue. In
fact, experienced programmers often joke that the only thing that separates them from junior
programmers is their ability to Google more quickly towards an answer. There is some truth to
this.
Not everything you read online can be trusted, of course, and with experience you will develop
the context to see how the pieces of Django and code in general fit together.
What to do if you are stuck on something in this book? As a first step, I recommend carefully
checking your code against what is in the book. If still stuck, you can look at the official source
Introduction 6
code which is available on GitHub5 . A common error is subtle white spacing differences that are
almost impossible to detect to the naked eye. You can try copy and pasting the official source
code if you suspect this might be the issue.
The next step is to walk away from the computer for a bit or even sleep on the problem. It’s
amazing what a small amount of rest and distance will do to your mind when it comes to solving
problems.
There are two fantastic online resources where the Django community gathers to ask and answer
questions. The first is the official Django Forum6 and the second is the Django Users Google
Group7 . Both are a good next step if you need additional help.
Community
The success of Django owes as much to its community as it does the technological achievement
of the framework itself. “Come for the framework, stay for the community” is a common saying
among Django developers. It extends to the technical development of Django, which happens
online via the django-developers8 , the non-profit Django Software Foundation9 that oversees
Django itself, annual DjangoCon conferences, and local meetups where developers gather to
share knowledge and insights.
No matter what your level of technical expertise becoming involved in Django itself is a great
way to learn, to meet other developers, and to enhance your own reputation.
Conclusion
In the next chapter you’ll learn how to properly set up your computer and create your first Django
project. Let’s begin!
5
https://github.com/wsvincent/djangoforbeginners
6
https://forum.djangoproject.com/
7
https://groups.google.com/g/django-users
8
https://docs.djangoproject.com/en/dev/internals/mailing-lists/#django-developers-mailing-list
9
https://www.djangoproject.com/foundation/
Chapter 1: Initial Set Up
This chapter covers how to properly configure your Windows or macOS computer to work on
Django projects. We start with an overview of the Command Line, a powerful text-only interface
that developers use extensively to install and configure Django projects. Then we install the latest
version of Python, learn how to create dedicated virtual environments, and install Django. As a
final step, we will explore using Git for version control and working with a text editor. By the end
of this chapter you will have created your first Django project from scratch and more importantly
be able to create and modify new Django projects in just a few keystrokes.
If you have ever seen a television show or movie where a hacker is furiously typing into a black
window: that’s the command line. It is an alternative to the mouse or finger-based graphical user
interface familiar to most computer users. An everyday computer user will never need to use the
command line but software developers do because certain tasks can only be done with it. These
include running programs, installing software, using Git for version control, or connecting to
servers in the cloud. With a little practice, most developers find that the command line is actually
a faster and more powerful way to navigate and control a computer.
Given its minimal user interface–just a blank screen and a blinking cursor–the command line
is intimidating to newcomers. There is often no feedback after a command has run and it is
possible to wipe the contents of an entire computer with a single command if you’re not careful:
no warning will pop up! As a result, the command line must be used with caution. Make sure
not to blindly copy and paste commands you find online; only rely on trusted resources for any
command you do not fully understand.
In practice, multiple terms are used to refer to the command line: Command Line Interface (CLI),
console, terminal, shell, or prompt. Technically speaking, the terminal is the program that opens
up a new window to access the command line, a console is a text-based application, the shell
Chapter 1: Initial Set Up 8
is the program that runs commands on the underlying operating system, and the prompt is
where commands are typed and run. It is easy to be confused by these terms initially but they
all essentially mean the same thing: the command line is where we run and execute text-only
commands on our computer.
On Windows, the built-in terminal and shell are both called PowerShell. To access it, locate the
taskbar on the bottom of the screen next to the Windows button and type in “powershell” to
launch the app. It will open a new window with a dark blue background and a blinking cursor
after the > prompt. Here is how it looks on my computer.
Shell
PS C:\Users\wsv>
Before the prompt is PS which refers to PowerShell, the initial C directory of the Windows
operating system, followed by the Users directory and the current user which, on my personal
computers, is wsv. Your username will obviously be different. At this point, don’t worry about
what comes to the left of the > prompt: it varies depending on each computer and can be
customized at a later date. The shorter prompt of > will be used going forward for Windows.
On macOS, the built-in terminal is called appropriately enough Terminal. It can be opened via
Spotlight: press the Command and space bar keys at the same time and then type in “terminal.”
Alternatively, open a new Finder window, navigate to the Applications directory, scroll down to
open the Utilities directory, and double-click the application called Terminal. This opens a new
screen with a white background by default and a blinking cursor after the % prompt. Don’t worry
about what comes to the left of the % prompt. It varies by computer and can be customized later
on.
Shell
Wills-Macbook-Pro:~ wsv%
If your macOS prompt is $ instead of % that means you are using Bash as the shell. Starting in
2019, macOS switched from Bash to zsh as the default shell. While most of the commands in this
book will work interchangeably, it is recommended to look up online how to change to zsh via
System Preferences if your computer still uses Bash.
Chapter 1: Initial Set Up 9
Shell Commands
There are many available shell commands but most developers rely on the same handful over
and over again and look up more complicated ones as needed.
In most cases, the commands for Windows (PowerShell) and macOS are similar. For example, the
command whoami returns the computer name/username on Windows and just the username on
macOS. As with all shell commands, type the command itself followed by the return key. Note
that the # symbol represents a comment and will not be executed on the command line.
Shell
# Windows
> whoami
wsv2021/wsv
# macOS
% whoami
wsv
Sometimes, however, the shell commands on Windows and macOS are completely different. A
good example is the command for outputting a basic “Hello, World!” message to the console. On
Windows the command is Write-Host while on macOS the command is echo.
Shell
# Windows
> Write-Host "Hello, World!"
Hello, World!
# macOS
% echo "Hello, World!"
Hello, World!
A frequent task on the command line is navigating within the computer filesystem. On Windows
and macOS the command pwd (print working directory) outputs the current location within the
file system.
Chapter 1: Initial Set Up 10
Shell
# Windows
> pwd
Path
----
C:\Users\wsv
# macOS
% pwd
/Users/wsv
You can save your Django code anywhere you like but for convenience we will place our code the
desktop directory. The command cd (change directory) followed by the intended location works
on both systems.
Shell
# Windows
> cd onedrive\desktop
> pwd
Path
----
C:\Users\wsv\onedrive\desktop
# macOS
% cd desktop
% pwd
/Users/wsv/desktop
Tip: The tab key will autocomplete a command so if you type cd d and then hit tab it will
automatically fill in the rest of the name. If there are more than two directories that start with d,
hit the tab key again to cycle through them.
To make a new directory use the command mkdir followed by the name. We will create one called
code on the Desktop and then within it a new directory called ch1-setup.
Chapter 1: Initial Set Up 11
Shell
# Windows
> mkdir code
> cd code
> mkdir ch1-setup
> cd ch1-setup
# macOS
% mkdir code
% cd code
% mkdir ch1-setup
% cd ch1-setup
You can check that it has been created by looking on your Desktop or running the command ls.
The full Windows output is slightly longer but is shortened here for conciseness.
Shell
# Windows
> ls
testdir
# macOS
% ls
testdir
Tip: The clear command will clear the Terminal of past commands and outputs so you have a
clean slate. The tab command autocompletes the line as we’ve discussed. And the ↑ and ↓ keys
cycle through previous commands to save yourself from typing the same thing over and over
again.
To exit you could close the Terminal with your mouse but the hacker way is to use use the
shell command exit instead. This works by default on Windows but on macOS the Terminal
preferences need to be changed. At the top of the screen click on Terminal, then Preferences
from the drop down menu. Click on Profiles in the top menu and then Shell from the list below.
There is a radio button for “When the shell exits:”. Select “Close the window.”
Chapter 1: Initial Set Up 12
Shell
# Windows
> exit
# macOS
% exit
Kinda cool, right? With practice, the command line is a far more efficient way to navigate and
operate your computer than using a mouse. For this book you don’t need to be a command line
expert: I will provide the exact instructions to run each time. But if you are curious, a complete
list of shell commands for each operating system can be found over at ss64.com.
On Windows, Microsoft hosts a community release of Python 3 in the Microsoft Store. In the
search bar on the bottom of your screen type in “python” and click on the best match result.
This will automatically launch Python 3.10 on the Microsoft Store. Click on the blue “Get” button
to download it.
To confirm Python was installed correctly, open a new Terminal window with PowerShell and
then type python --version.
Shell
The result should be at least Python 3.10. Then type python to open the Python interpreter from
the command line shell.
Chapter 1: Initial Set Up 13
Shell
> python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 19:00:18)
[MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Mac, the official installer on the Python website is the best approach. In a new browser
window go the Python downloads page10 and click on the button underneath the text “Download
the latest version for Mac OS X.” As of this writing, that is Python 3.10. The package will be in your
Downloads directory. Double click on it which launches the Python Installer and follow through
the prompts.
To confirm the download was successful, open up a new Terminal window and type python3
--version.
Shell
% python3 --version
Python 3.10.2
The result should be at least 3.10. Then type python3 to open the Python interpreter.
10
https://www.python.org/downloads/
Chapter 1: Initial Set Up 14
Shell
% python3
Python 3.10.2 (v3.10.2:a58ebcc701, Jan 13 2022, 14:50:16)
[Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
From the command line typing either python on Windows or python3 on macOS will bring up the
Python Interpreter, also known as Python Interactive mode. The new prompt of >>> indicates
that you are now inside Python itself and not the command line. If you try any of the previous
shell commands we ran–cd, ls, mkdir–they will each raise errors. What will work is actual Python
code. For example, try out both 1 + 1 and print("Hello Python!") making sure to hit the Enter
or Return key after each to run them.
Shell
>>> 1 + 1
2
>>> print("Hello Python!")
Hello Python!
Python’s interactive mode is a great way to save time if you want to try out a short bit of Python
code. But it has a number of limitations: you can’t save your work in a file and writing longer code
snippets is cumbersome. As a result, we will spend most of our time writing Python and Django
in files using a text editor.
To exit Python from the command line you can type either exit() and the Enter key or use Ctrl
+ z on Windows or Ctrl + d on macOS.
Virtual Environments
Installing the latest version of Python and Django is the correct approach for any new project.
But in the real world, it is common that existing projects rely on older versions of each. Consider
Chapter 1: Initial Set Up 15
the following situation: Project A uses Django 2.2 but Project B uses Django 4.0? By default, Python
and Django are installed globally on a computer meaning it is quite a pain to install and reinstall
different versions every time you want to switch between projects.
Fortunately, there is a straightforward solution. Virtual environments allow you to create and
manage separate environments for each Python project on the same computer. There are many
areas of software development that are hotly debated, but using virtual environments for Python
development is not one. You should use a dedicated virtual environment for each new Python
project.
There are several ways to implement virtual environments but the simplest is with the venv11
module already installed as part of the Python 3 standard library. To try it out, navigate to the
existing ch1-setup directory on your Desktop.
Shell
# Windows
> cd onedrive\desktop\code\ch1-setup
# macOS
% cd ~/desktop/code/ch1-setup
To create a virtual environment within this new directory use the format python -m venv <name_-
of_env> on Windows or python3 -m venv <name_of_env> on macOS. It is up to the developer to
11
https://docs.python.org/3/library/venv.html
Chapter 1: Initial Set Up 16
Shell
# Windows
> python -m venv .venv
> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# macOS
% python3 -m venv .venv
If you use the command ls to look at our current directory it will appear empty. However the
.venv directory is there, it’s just that it is “hidden” due to the period . that precedes the name.
Hidden files and directories are a way for developers to indicate that the contents are important
and should be treated differently than regular files. To view it, try ls -la which shows all
directories and files, even hidden ones.
Shell
> ls -la
total 0
drwxr-xr-x 3 wsv staff 96 Dec 12 11:10 .
drwxr-xr-x 3 wsv staff 96 Dec 12 11:10 ..
drwxr-xr-x 6 wsv staff 192 Dec 12 11:10 .venv
You will see that .venv is there and can be accessed via cd if desired. In the directory itself is a
copy of the Python interpreter and a few management scripts, but you will not need to use it
directly in this book.
Once created, a virtual environment must be activated. On Windows an Execution Policy must
be set to enable running scripts. This is a safety precaution. The Python docs12 recommend
allowing scripts for the CurrentUser only, which is what we will do. On macOS there are no
similar restrictions on scripts so it is possible to directly run source .venv/bin/activate.
Here is what the full commands look like to create and activate a new virtual environment called
.venv:
12
https://docs.python.org/3/library/venv.html
Chapter 1: Initial Set Up 17
Shell
# Windows
> python -m venv .venv
> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
> .venv\Scripts\Activate.ps1
(.venv) >
# macOS
% python3 -m venv .venv
% source .venv/bin/activate
(.venv) %
The shell prompt now has the environment name (.venv) prefixed which indicates that the
virtual environment is active. Any Python packages installed or updated within this location will
be confined to the active virtual environment.
Shell
# Windows
(.venv) > deactivate
>
# macOS
(.venv) % deactivate
%
The shell prompt no longer has the virtual environment name prefixed which means the session
is now back to normal.
Install Django
Now that Python is installed and we know how to use virtual environments it is time to install
Django for the first time. In the ch1-setup directory reactivate the existing virtual environment.
Chapter 1: Initial Set Up 18
Shell
# Windows
> .venv\Scripts\Activate.ps1
(.venv) >
# macOS
% source .venv/bin/activate
(.venv) %
Django is hosted on the Python Package Index (PyPI)13 , a central repository for most Python
packages. We will use pip, the most popular package installer, which comes included with
Python 3. To install the latest version of Django use the command python -m pip install
django∼=4.0.0.
The comparison operator ∼= ensures that subsequent security updates for Django, such as 4.0.1,
4.0.2, and so on are automatically installed. Note that while it is possible to use the shorter version
of pip install <package>, it is a best practice to use the longer but more explicit form of python
-m pip install <package> to ensure that the correct version of Python is used. This can be an
Shell
You might see a WARNING message about updating pip after running these commands. It’s always
good to be on the latest version of software and to remove the annoying WARNING message each
time you use pip. You can either copy and paste the recommended command or run python -m
pip install --upgrade pip to be on the latest version.
Shell
13
https://pypi.org
Chapter 1: Initial Set Up 19
A Django project can have almost any name but we will use django_project in this book. To
create a new Django project use the command django-admin startproject django_project .
Shell
It’s worth pausing here to explain why you should add a period (.) to the end of the previous
command. If you just run django-admin startproject django_project then by default Django
will create this directory structure:
Layout
django_project/
├── django_project
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── .venv/
Do you see the multiple django_project directories? First a top-level django_project directory
is created and then another one within it that contains the files we need for our Django project.
This feels redundant to me which is why I prefer adding a period to the end which installs Django
in the current directory.
Chapter 1: Initial Set Up 20
Layout
├── django_project
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── .venv/
As you progress in your journey learning Django, you’ll start to bump up more and more into
similar situations where there are different opinions within the Django community on the correct
best practice. Django is eminently customizable, which is a great strength, however the tradeoff
is that this flexibility comes at the cost of seeming complexity. Generally speaking, it’s a good
idea to research any such issues that arise, make a decision, and then stick with it!
Now let’s confirm everything is working by running Django’s internal web server via the
runserver command. This is suitable for local development purposes, but when it comes time
to deploy our project’s online we will switch to a more robust WSGI server like Gunicorn.
Shell
# Windows
(.venv) > python manage.py runserver
# macOS
(.venv) % python3 manage.py runserver
You have 18 unapplied migration(s). Your project may not work properly until
you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
Don’t worry about the text in red about 18 unapplied migrations. We’ll get to that shortly. The
important part, for now, is to visit http://127.0.0.1:8000/ in your web browser and make sure
the following image is visible:
If you are on Windows you’ll see the final line says to use CONTROL-BREAK to quit whereas on
macOS it is CONTROL-C. Newer Windows keyboards often do not have a Pause/Break key in which
Chapter 1: Initial Set Up 22
As a side note, it is also possible to visit http://localhost:8000 to see the running Django web-
site. There are two ways to visit a local port number on your machine. I default to 127.0.0.1:8000
in this book because that is what Django outputs in the terminal but either is okay to use in
practice.
Go ahead and stop the local server with the appropriate command and then exit the virtual
environment by typing deactivate and hitting Return.
Shell
# Windows or macOS
(.venv) > deactivate
We’ll get lots of practice with virtual environments in this book so don’t worry if it’s a little
confusing right now. The basic pattern for any new Django project is to first make and activate
a virtual environment, install Django, and then run startproject.
It’s worth noting that only one virtual environment can be active in a command line tab at a time.
In future chapters we will be creating a brand new virtual environment for each new project so
either make sure to deactivate your current environment or open up a new tab for new projects.
Text Editors
The command line is where we execute commands for our programs but a text editor is where
actual code is written. The computer doesn’t care what text editor you use–the end result is just
code–but a good text editor can provide helpful hints and catch typos for you.
There are many modern text editors available but a very popular one is Visual Studio Code14 ,
which is free, easy to install, and enjoys widespread popularity. If you’re not already using a text
editor, download and install VSCode from the official website.
Extensions or on macOS Code -> Preferences -> Extensions. This launches a search bar
for the extensions marketplace. Enter “python” which will bring up the Microsoft extension as
the first result. Install it.
A second extension to add is Black15 , which is a Python code formatter that has quickly become
the default within the Python community. To install Black, open a Terminal window within
VSCode by going to Terminal -> New Terminal at the top of the page. In the new terminal
window opened at the bottom of the page, type python -m pip install black. Next, open up
the VSCode settings by navigating to File -> Preferences -> Settings on Windows or Code
-> Preferences -> Settings on macOS. Search for “python formatting provider” and select
black from the dropdown options. Then search for “format on save” and enable “Editor: Format
on Save”. Black will now automatically format your code whenever a *.py file is saved.
To confirm this is working, use your text editor to create a new file called hello.py within the
ch1-setup directory. located on your Desktop and type in the following using single quotes:
hello.py
print('Hello, World!')
On save, it should be automatically updated to using double quotes which is Black’s default
preference16 : print("Hello, World!"). That means everything is working properly.
Install Git
The final step is to install Git, a version control system that is indispensable to modern software
development. With Git you can collaborate with other developers, track all your work via
commits, and revert to any previous version of your code even if you accidentally delete
something important!
On Windows, navigate to the official website at https://git-scm.com/ and click on the “Down-
load” link which should install the proper version for your computer. Save the file and then open
your Downloads folder and double click on the file. This will launch the Git for Windows installer.
15
https://pypi.org/project/black/
16
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#strings
Chapter 1: Initial Set Up 24
Click the “Next” button through most of the early defaults as they are fine and can always be
updated later as needed. There are two exceptions however: under “Choosing the default editor
used by Git” select VS Code not Vim. And in the section on “Adjusting the name of the initial
branch in new repositories” select the option to use “main” as opposed to “master” as the default
branch name. Otherwise the recommended defaults are fine and can always be tweaked later if
needed.
To confirm Git is installed on Windows, close all current shell windows and then open a new one
which will load the changes to our PATH variable. Type in git --version which should show it
is installed.
Shell
# Windows
> git --version
git version 2.33.1.windows.1
On macOS, installing Git via Xcode is currently the easiest option. To check if Git is already
installed on your computer, type git --version in a new terminal window.
Shell
# macOS
% git --version
If you do not have Git installed, a popup message will ask if you want to install it as part of
“command line developer tools.” Select “Install” which will load Xcode and its command line tools
package. Or if you do not see the message for some reason, type xcode-select --install instead
to install Xcode directly.
Be aware that Xcode is a very large package so the initial download may take some time. Xcode
is primarily designed for building iOS apps but also includes many developer features need on
macOS. Once the download is complete close all existing terminal shells, open a new window,
and type in git --version to confirm the install worked.
Chapter 1: Initial Set Up 25
Shell
# macOS
% git --version
git version 2.30.1 (Apple Git-130)
Once Git is installed on your machine we need to do a one-time system configuration by declaring
the name and email address associated with all your Git commits. We will also set the default
branch name to main. Within the command line shell type the following two lines. Make sure to
update them your name and email address.
Shell
You can always change these configs later if you desire by retyping the same commands with a
new name or email address.
Conclusion
If you become stuck at any point, complete source code for this and all future chapters is available
online on the official GitHub repo17 for the book.
Initial Set Up
To begin, open up a new command line shell or use the built-in terminal on VS Code. For the
latter click on “Terminal” at the top and then “New Terminal” to bring it up on the bottom of the
screen.
Make sure you are not in an existing virtual environment by checking there is nothing in
parentheses before your command line prompt. You can even type deactivate to be completely
sure. Then navigate to the code directory on your Desktop and create a helloworld directory
with the following commands.
17
https://github.com/wsvincent/djangoforbeginners
Chapter 2: Hello World App 27
Shell
# Windows
> cd onedrive\desktop\code
> mkdir helloworld
> cd helloworld
# macOS
% cd ~/desktop/code
% mkdir helloworld
% cd helloworld
Create a new virtual environment called .venv, activate it, and install Django with Pip as we did
in the previous chapter.
Shell
# Windows
> python -m venv .venv
> .venv\Scripts\Activate.ps1
(.venv) > python -m pip install django~=4.0.0
# macOS
% python3 -m venv .venv
% source .venv/bin/activate
(.venv) % python3 -m pip install django~=4.0.0
Now we’ll use the Django startproject command to make a new project called django_project.
Don’t forget to include the period (.) at the end of the command so that it is installed in our
current directory.
Shell
Let’s pause for a moment to examine the default project structure Django has provided for us. You
examine this visually if you like by opening the new directory with your mouse on the Desktop.
The .venv directory may not be initially visible because it is “hidden” but nonetheless still there.
Chapter 2: Hello World App 28
Code
├── django_project
│ ├── __init__.py
| ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── .venv/
The .venv directory was created with our virtual environment but Django has added a django_-
project directory and a manage.py file. Within django_project are five new files:
• __init__.py indicates that the files in the folder are part of a Python package. Without
this file, we cannot import files from another directory which we will be doing a lot of in
Django!
• asgi.py allows for an optional Asynchronous Server Gateway Interface18 to be run
• settings.py controls our Django project’s overall settings
• urls.py tells Django which pages to build in response to a browser or URL request
• wsgi.py stands for Web Server Gateway Interface19 which helps Django serve our eventual
web pages.
The manage.py file is not part of django_project but is used to execute various Django com-
mands such as running the local web server or creating a new app.
Let’s try out our new project by using Django’s lightweight built-in web server for local
development purposes. The command we’ll use is runserver which is located in manage.py.
18
https://asgi.readthedocs.io/en/latest/specs/main.html
19
https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
Chapter 2: Hello World App 29
Shell
# Windows
(.venv) > python manage.py runserver
# macOS
(.venv) % python3 manage.py runserver
Note that the full command line output will contain additional information including a warning
about 18 unapplied migrations. Technically, this warning doesn’t matter at this point. Django
is complaining that we have not yet “migrated” our initial database. Since we won’t actually use
a database in this chapter the warning won’t affect the end result.
However, since warnings are still annoying to see, we can remove it by first stopping the local
Chapter 2: Hello World App 31
server with the command Control+c and then running python manage.py migrate.
Shell
# Windows
> python manage.py migrate
# macOS
% python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
What Django has done here is create a SQLite database and migrated its built-in apps provided
for us. This is represented by the new file db.sqlite3 in our directly.
Chapter 2: Hello World App 32
Code
├── django_project
│ ├── __init__.py
| ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3 # new
├── manage.py
└── .venv/
For now, if you execute python manage.py runserver again you should no longer see any
warnings.
HTTP (Hypertext Transfer Protocol)20 was initially created by Tim Berners-Lee in 1989 and is
the foundation of the World Wide Web. A network protocol is a set of rules for formatting and
processing data. It is like a common language for computers that allows them to communicate
with one another even if they are located on opposite sides of the earth and have vastly different
hardware and software.
HTTP is a request-response protocol that works in a client-server computing model. Every time
you visit a webpage an initial “request” is sent by the “client” (ie your computer) and a “response”
is sent back by a “server.” The client doesn’t have to be a computer though, it could also be a
mobile phone or any internet-connected device. But the process is the same: an HTTP request
is sent to a URL by a client and a server sends back an HTTP response.
Ultimately, all a web framework like Django does is accept HTTP requests to a given URL and
return a HTTP response containing the information necessary to render a webpage. That’s it.
Generally this process involves identifying the proper URL, connecting to a database, adding
some logic, applying style with HTML/CSS/JavaScript/static assets, and then return the HTTP
response. That’s it.
Web Framework
HTTP Request -> URL -> Django combines database, logic, styling -> HTTP Response
Model-View-Controller vs Model-View-Template
Over time the Model-View-Controller (MVC) pattern has emerged as a popular way to internally
separate the data, logic, and display of an application into separate components. This makes it
easier for a developer to reason about the code. The MVC pattern is widely used among web
frameworks including Ruby on Rails, Spring (Java), Laravel (PHP), ASP.NET (C#) and many others.
Django only loosely follows the traditional MVC approach with its own version often called
Model-View-Template (MVT). This can be initially confusing to developers with previous web
framework experience. In reality, Django’s approach is really it is a 4-part pattern that also
incorporates URL Configuration so something like MVTU would be a more accurate description.
This interaction is fundamental to Django yet very confusing to newcomers so let’s map
out the order of a given HTTP request/response cycle. When you type in a URL, such as
https://djangoproject.com, the first thing that happens within our Django project is a URL
pattern (contained in urls.py) is found that matches it. The URL pattern is linked to a single
Chapter 2: Hello World App 34
view (contained in views.py) which combines the data from the model (stored in models.py) and
the styling from a template (any file ending in .html). The view then returns a HTTP response to
the user.
HTTP Request -> URL -> View -> Model and Template -> HTTP Response
If you are brand new to web development the distinction between MVC and MVT will not matter
much. This book demonstrates the Django way of doing things so there won’t be confusion.
However if you are a web developer with previous MVC experience, it can take a little while
to shift your thinking to the “Django way” of doing things which is more loosely coupled and
allows for easier modifications.
Create An App
Django uses the concept of projects and apps to keep code clean and readable. A single top-level
Django project can contain multiple apps. Each app controls an isolated piece of functionality.
For example, an e-commerce site might have one app for user authentication, another app
for payments, and a third app to power item listing details. That’s three distinct apps that all
live within one top-level project. How and when you split functionality into apps is somewhat
subjective, but in general, each app should have a clear function.
To add a new app go to the command line and quit the running server with Control+c. Then use
the startapp command followed by the name of our app which will be pages.
Chapter 2: Hello World App 35
Shell
# Windows
(.venv) > python manage.py startapp pages
# macOS
(.venv) % python3 manage.py startapp pages
If you look visually at the helloworld directory Django has created within it a new pages directory
containing the following files:
Code
├── pages
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
Notice that the model, view, and url from the MVT pattern are present from the beginning. The
only thing missing is a template which we’ll add shortly.
Even though our new app exists within the Django project, Django doesn’t “know” about it until
we explicitly add it to the django_project/settings.py file. In your text editor open the file up
Chapter 2: Hello World App 36
and scroll down to INSTALLED_APPS where you’ll see six built-in Django apps already there. Add
pages.apps.PagesConfig at the bottom.
Code
# django_project/settings.py
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"pages.apps.PagesConfig", # new
]
If you have Black installed in your text editor on “save” it will change all the single quotes '' here
to double quotes "". That’s fine. As noted previously, Django has plans to adopt Black Python
formatting fully in the future.
What is PagesConfig you might ask? Well, it is the name of the solitary function within the
pages/apps.py file at this point.
Code
# pages/apps.py
from django.apps import AppConfig
class PagesConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "pages"
Don’t worry if you are confused at this point: it takes practice to internalize how Django projects
and apps are structured. Over the course of this book we will build many projects and apps and
the patterns will soon become familiar.
Hello, World
In Django, four separate files aligning with this MVT pattern are required to power one single
dynamic (aka linked to a database) webpage:
Chapter 2: Hello World App 37
• models.py
• views.py
• template.html (any HTML file will do)
• urls.py
However, to create a static webpage (not linked to a database) we can hardcode the data into a
view so the model is not needed. That’s what we’ll do here to keep things simple. From Chapter
4 onwards we’ll be using the model in all our projects.
The next step is therefore to create our first view. Start by updating the views.py file in our
pages app to look as follows:
Code
# pages/views.py
from django.http import HttpResponse
def homePageView(request):
return HttpResponse("Hello, World!")
Basically, we’re saying whenever the view function homePageView is called, return the text “Hello,
World!” More specifically, we’ve imported the built-in HttpResponse21 method so we can return
a response object to the user. We’ve created a function called homePageView that accepts the
request object and returns a response with the string “Hello, World!”
There are two types of views in Django: function-based views (FBVs) and class-based views (CBVs).
Our code in this example is a function-based view: it is relatively simple to implement and explicit.
Django originally started with only FBVs but over time added CBVs which allow for much greater
code reusability, keeps things DRY (Don’t-Repeat-Yourself), and can be extended via mixins. The
additional abstraction of CBVs makes them quite powerful and concise, however it also makes
them harder to read for Django newcomers.
Because web development quickly becomes repetitive Django also comes with a number of built-
in generic class-based views (GCBVs) to handle common use cases such as creating a new object,
21
https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpResponse
Chapter 2: Hello World App 38
forms, list views, pagination, and so on. We will be using GCBVs heavily in this book in later
chapters.
There are therefore technically three ways to write a view in Django: function-based views (FBVs),
class-based views (CBVs), and generic class-based views (GCBVs). This customization is helpful
for advanced developers but confusing for newcomers. Many Django developers–including your
author–prefer to use GCBVs when possible and revert to CBVs or FBVs when required. By the
end of this book you will have used all three and can make up your own mind on which approach
you prefer.
Moving along we need to configure our URLs. In your text editor, create a new file called urls.py
within the pages app. Then update it with the following code:
Code
# pages/urls.py
from django.urls import path
from .views import homePageView
urlpatterns = [
path("", homePageView, name="home"),
]
On the top line we import path from Django to power our URL pattern and on the next line we
import our views. By referring to the views.py file as .views we are telling Django to look within
the current directory for a views.py file and import the view homePageView from there.
In other words, if the user requests the homepage represented by the empty string "", Django
should use the view called homePageView.
22
https://docs.djangoproject.com/en/4.0/topics/http/urls/#naming-url-patterns
Chapter 2: Hello World App 39
We’re almost done at this point. The last step is to update our django_project/urls.py file. It’s
common to have multiple apps within a single Django project, like pages here, and they each
need their own dedicated URL path.
Code
# django_project/urls.py
from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("pages.urls")), # new
]
We’ve imported include on the second line next to path and then created a new URL pattern for
our pages app. Now whenever a user visits the homepage, they will first be routed to the pages
app and then to the homePageView view set in the pages/urls.py file.
This need for two separate urls.py files is often confusing to beginners. Think of the top-level
django_project/urls.py as the gateway to various url patterns distinct to each app.
We have all the code we need now. To confirm everything works as expected, restart our Django
server:
Shell
# Windows
(.venv) > python manage.py runserver
# macOS
(.venv) % python3 manage.py runserver
If you refresh the browser for http://127.0.0.1:8000/ it now displays the text “Hello, World!”
Git
In the previous chapter we installed the version control system Git. Let’s use it here. The first
step is to initialize (or add) Git to our repository. Make sure you’ve stopped the local server with
Control+c, then run the command git init.
Shell
If you then type git status you’ll see a list of changes since the last Git commit. Since this is our
first commit, this list is all of our changes so far.
Shell
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
.venv
django_project/
db.sqlite3
manage.py
pages/
nothing added to commit but untracked files present (use "git add" to track)
Note that our virtual environment .venv is included which is not a best practice. It should be
kept out of Git source control since secret information such as API keys and the like are often
included in it. The solution is to create a new file called .gitignore which tells Git what to
ignore. The period at the beginning indicates this is a “hidden” file. The file still exists but it is a
way to communicate to developers that the contents are probably meant for configuration and
not source control. In this new file, add a single line for .venv.
Chapter 2: Hello World App 41
.gitignore
.venv/
If you run git status again you will see that .venv is not longer there. It has been “ignored” by
Git.
At the same time, we do want a record of packages installed in our virtual environment. The cur-
rent best practice is to create a requirements.txt file with this information. The command pip
freeze will output the contents of your current virtual environment and by using the > operator
we can do all this in one step: output the contents into a new file called requirements.txt. If
your server is still running enter Ctrl+c and Enter to exit before entering this command.
Shell
A new requirements.txt file will appear with all our installed packages and their dependencies.
If you look inside this file you’ll see there are actually four packages even though we have installed
only one.
requirements.txt
asgiref==3.4.1
Django==4.0
sqlparse==0.4.2
That’s because Django relies on other packages for support, too. It is often the case that when
you install one Python package you’re often installing several others it depends on as well. Since
it is difficult to keep track of all the packages a requirements.txt file is very important.
We next want to add all recent changes by using the command add -A and then commit the
changes along with a message (-m) describing what has changed.
Another Random Document on
Scribd Without Any Related Topics
comfortingly. Put away your evil habits, one after another, because
they are evil, not simply because they hurt you. Get up a rebellion in
your spirit against wrong ways of living. Resolve that you will not live
wrongly; characterize that way as it should be characterized, as an
improper, unmanly, mean, or unbefitting way for you. Say: I will not
smoke; I will not drink; I will not make my body an instrument of
gluttony; and so go through your whole round of habits, putting
away all those that you can get along without. Reduce your artificial
wants to a minimum. Throw yourself over on the line of order and
law, and regularity and propriety. Then you will get well.”
APPENDIX TO SECOND EDITION.
The person who works to-day and gets tired, perhaps almost
exhausted, feels sure from former experiences that he will rise next
morning well able to work again; and providing he does not
overdraw the account continually, the more he does the more he can
do. It is upon this principle that our athletes acquire and maintain
condition.
FROM A TEACHER.
FROM A HUSBAND.
SPECIAL NOTE.
Fruit vs. Fish, Flesh, Fowl & Co. in Hot Weather, 191
Fruit in Winter, 211
Food Poisonous Unless Digested, 246
Food and Virtue, 53, 265
Fæces, Source of the, 111
Foul Air, Poor Economy to Save, 87
Food, The Natural, of Man, 48, 72, 207
Food, “Rich,” Injurious, 88, 153
Hot or Cold?, 99
Fasts, Professional, Value of, 74
Fasting, Notable Instances of, 72, 73, 140, 168
Fasting, Constipation Normal during, 107, 112
Fasting Cure, The, 42, 43, 145, 153, 168
Food as a Purgative, 113, 114, 194
Fatty Degeneration, 79, 80, 148, 150
Obesity not a Requisite of, 79
Fever, 153
Food, Raw, and Health, 17, 223, 224
Flies and Health, 97
Fruit, 94, 191, 194
Food, The Quantity of, Relation of Climate to, 117
Fruit vs. Physic, 194
Fossil Bodies, 24, 183, 246
Livers, 179
Fasting and Insanity, 140
Flesh-food Fallacy, The, 158
and Bread Compared, 159
Often Diseased, 160
Question, Moral Aspect of the, 163
Flesh-food and Heredity, 164
Unfairness of the Advocates of, 160
Franklin’s Idea of “Colds”, 171
IN
AN ALLEGORY.
The “Foundations,” which are the bones. The “Walls” are the
muscles, while the skin and hair are called the “Siding and Shingles.”
The head is an “Observatory” in which are found a pair of
“Telescopes,” and radiating from it are the nerves compared to a
“Telegraph” and “Phonograph.” The communications are kept up
with the “Kitchen,” “Dining-Room,” “Butler’s Pantry,” “Laundry,” and
“Engine.” The house is heated by a “Furnace,” which is also a “Sugar
Manufactory.” Nor is the house without mystery, for it contains a
number of “Mysterious Chambers.” It is protected by a wonderful
“Burglar Alarm,” and watched over by various “Guardians.” A pair of
charming “Windows” adorn the “Façade,” and a “Whispering Gallery”
offers a delightful labyrinth for our wanderings.
ebookbell.com