0% found this document useful (0 votes)
20 views

Django For Beginners Build Websites With Python Django download

The document is an overview of the book 'Django for Beginners' by William S. Vincent, which aims to teach web development using the Django framework through a project-based approach. It outlines the book's structure, which includes building various web applications, and emphasizes the importance of Django's features and community support. The author aims to provide a beginner-friendly resource to help new developers effectively learn and use Django for their projects.

Uploaded by

islaneeget
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Django For Beginners Build Websites With Python Django download

The document is an overview of the book 'Django for Beginners' by William S. Vincent, which aims to teach web development using the Django framework through a project-based approach. It outlines the book's structure, which includes building various web applications, and emphasizes the importance of Django's features and community support. The author aims to provide a beginner-friendly resource to help new developers effectively learn and use Django for their projects.

Uploaded by

islaneeget
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Django For Beginners Build Websites With Python

Django download

https://ebookbell.com/product/django-for-beginners-build-
websites-with-python-django-43712546

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Django For Beginners Build Websites With Python Django 40 William S


Vincent

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

Django For Beginners 31 31 William S Vincent

https://ebookbell.com/product/django-for-beginners-31-31-william-s-
vincent-22471298

Django For Beginners William S Vincent

https://ebookbell.com/product/django-for-beginners-william-s-
vincent-56458436

Django For Beginners Converted William S Vincent

https://ebookbell.com/product/django-for-beginners-converted-william-
s-vincent-56537090

Django For Beginners William S Vincent

https://ebookbell.com/product/django-for-beginners-william-s-
vincent-44609942
Django for Beginners

Build websites with Python & Django

William S. Vincent

This book is for sale at http://leanpub.com/djangoforbeginners

This version was published on 2022-03-24

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.

© 2018 - 2022 William S. Vincent


Also By William S. Vincent
Django for APIs

Django for Professionals


Contents

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

Chapter 1: Initial Set Up 7


The Command Line 7
Shell Commands 9
Install Python 3 on Windows 12
Install Python 3 on Mac 13
Python Interactive Mode 14
Virtual Environments 14
Install Django 17
First Django Project 19
Text Editors 22
Install Git 23
Conclusion 25

Chapter 2: Hello World App 26


Initial Set Up 26
CONTENTS

HTTP Request/Response Cycle 32


Model-View-Controller vs Model-View-Template 33
Create An App 34
Hello, World 36
Git 40
GitHub 42
SSH Keys 43
Conclusion 44

Chapter 3: Pages App 45


Initial Set Up 45
Templates 48
Class-Based Views 49
URLs 50
About Page 51
Extending Templates 53
Tests 55
Git and GitHub 60
Local vs Production 62
Heroku 62
Deployment Checklist 64
Conclusion 69

Chapter 4: Message Board App 70


Initial Set Up 70
Create a Database Model 73
Activating models 74
Django Admin 75
Views/Templates/URLs 80
Adding New Posts 83
Tests 84
GitHub 88
Heroku Configuration 89
CONTENTS

Heroku Deployment 90
Conclusion 91

Chapter 5: Blog App 92


Initial Set Up 92
Database Models 95
Admin 96
URLs 100
Views 101
Templates 102
Static Files 104
Individual Blog Pages 109
Tests 113
Git 117
Conclusion 118

Chapter 6: Forms 119


CreateView 119
UpdateView 125
DeleteView 129
Tests 134
Conclusion 136

Chapter 7: User Accounts 137


Log In 137
Updated Homepage 140
Log Out Link 141
Sign Up 144
Sign Up Link 149
GitHub 150
Static Files 151
Heroku Config 154
Heroku Deployment 155
CONTENTS

SQLite vs PostgreSQL 156


Conclusion 157

Chapter 8: Custom User Model 158


Initial Set Up 158
Custom User Model 159
Forms 161
Superuser 164
Conclusion 168

Chapter 9: User Authentication 169


Templates 169
URLs 172
Admin 176
Tests 181
Conclusion 183

Chapter 10: Bootstrap 184


Pages App 184
Tests 187
Testing Philosophy 188
Bootstrap 188
Sign Up Form 193
Conclusion 198

Chapter 11: Password Change and Reset 199


Password Change 199
Customizing Password Change 200
Password Reset 203
Custom Templates 207
Try It Out 210
Conclusion 212

Chapter 12: Email 213


CONTENTS

SendGrid 213
Custom Emails 220
Conclusion 222

Chapter 13: Newspaper App 223


Articles App 223
URLs and Views 227
Detail/Edit/Delete 231
Create Page 237
Conclusion 242

Chapter 14: Permissions and Authorization 243


Improved CreateView 243
Authorizations 245
Mixins 247
LoginRequiredMixin 249
UpdateView and DeleteView 251
Conclusion 253

Chapter 15: Comments 254


Model 254
Admin 255
Template 264
Comment Form 268
Comment View 269
Comment Template 270
Comment Post View 272
Conclusion 277

Chapter 16: Deployment 278


Environment Variables 279
DEBUG & ALLOWED HOSTS 281
SECRET_KEY 284
CONTENTS

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

• database models, forms, URL routes, and templates


• admin interface
• security and performance upgrades
• support for multiple database backends

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.

Why This Book

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

takes just a few mouse clicks.

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

# This is Python code


print("Hello, World!")

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

Advice on Getting Stuck

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.

The Command Line

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.

Install Python 3 on Windows

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

> python --version


Python 3.10.2

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.
>>>

Install Python 3 on Mac

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.
>>>

Python Interactive Mode

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

choose a proper environment name but a common choice is to call it .venv.

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.

To deactivate and leave a virtual environment type deactivate.

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

issue if you have multiple versions of Python installed on your computer.

Shell

(.venv) > python -m pip install django~=4.0.0

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

(.venv) > python -m pip install --upgrade pip

13
https://pypi.org
Chapter 1: Initial Set Up 19

First Django Project

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

(.venv) > django-admin startproject django_project .

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

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).

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.

December 12, 2021 - 15:26:23


Django version 4.0.0, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-BREAK.
Chapter 1: Initial Set Up 21

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:

Django welcome page

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

case using the c key usually works.

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.

An optional–but highly recommended–additional step is to take advance of the large ecosys-


tem of extensions available on VSCode. On Windows, navigate to File -> Preferences ->
14
https://code.visualstudio.com/
Chapter 1: Initial Set Up 23

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

> git config --global user.name "Your Name"


> git config --global user.email "[email protected]"
> git config --global init.defaultBranch main

You can always change these configs later if you desire by retyping the same commands with a
new name or email address.

Conclusion

Phew! It is no easy task to configure a software development environment. But fortunately it


is a one-time pain and will pay many dividends done the road. We have now learned about the
command line, Python interactive mode, installed the latest version of Python, Django and Git,
and configured our text editor. Everything is ready for our first Django app in the next chapter.
Chapter 2: Hello World App
In this chapter we will build a Django project that simply says “Hello, World” on the homepage.
This is the traditional way to start a new programming language or framework. We’ll also work
with Git for the first time and deploy our code to GitHub.

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

(.venv) > django-admin startproject django_project .

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

If you visit http://127.0.0.1:8000/ you should see the following image:


Chapter 2: Hello World App 30

Django welcome page

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 Request/Response Cycle

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.

The abstract flow looks something like this:


20
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
Chapter 2: Hello World App 33

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.

In the traditional MVC pattern there are three major components:

• Model: Manages data and core business logic


• View: Renders data from the model in a particular format
• Controller: Accepts user input and performs application-specific logic

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.

The Django MVT pattern is as follows:

• Model: Manages data and core business logic


• View: Describes which data is sent to the user but not its presentation
• Template: Presents the data as HTML with optional CSS, JavaScript, and Static Assets
• URL Configuration: Regular-expression components configured to a View

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.

The complete Django flow looks like this:

Django request/response cycle

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

Let’s review what each new pages app file does:

• admin.py is a configuration file for the built-in Django Admin app


• apps.py is a configuration file for the app itself
• migrations/ keeps track of any changes to our models.py file so it stays in sync with our
database
• models.py is where we define our database models which Django automatically translates
into database tables
• tests.py is for app-specific tests
• views.py is where we handle the request/response logic for our web app

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.

Our URL pattern has three parts:

• a Python regular expression for the empty string ""


• a reference to the view called homePageView
• an optional named URL pattern22 called "home"

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!”

Hello World homepage


Chapter 2: Hello World App 40

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

(.venv) > git init

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

(.venv) > git status


On branch main

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

(.venv) > pip freeze > requirements.txt

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.

1 [NOTE ON DEEP BREATHING.]

A Good Hobby.—On pages 84, 111, and 137 I have barely


touched upon this subject. I wish now to call attention to it as a
matter worthy of greater consideration than might perhaps be
gathered from what has been said. Personally, I begun the practice,
when I was about sixteen years old, of taking long, deep breaths
occasionally, at odd times during the day, from reading a little slip
explaining its usefulness in “strengthening” the lungs, and increasing
their capacity. At the age of eighteen, I remember, upon being
examined for a life insurance policy, the examining surgeon
expressed great surprise at the unusual “swell” or expansion of my
chest—about five inches increase when my lungs were fully inflated,
over chest-measure when I had forced out as much air as I could
conveniently. Upon explaining, that for a number of years I had
made a practice of throwing my shoulders back, taking very deep
inspirations slowly, holding my breath a moment, and then as slowly
“breathing out”—doing this the first thing every morning on rising,
and in a sleeping-room which was never close, again on going out,
and occasionally during the day,—the doctor said: “A good plan that
accounts for it.” In all cases of weak lungs, whether chronic or from
“taking cold” (see pp. 40 to 45 for a consideration of the colds
delusion), when it is difficult to take a full breath on account of
“cramps,” catches, or pain in the lungs, this practice will be found of
great value, if persisted in. In many instances it seems impossible to
take a long breath—is, indeed, impossible; but a little gain may be
made every day, by crowding down “one notch,” so to say, at each
trial. Quite a large percentage of all persons will find on trial that
there is more or less of tenderness upon first making the attempt, or
at one time or another, whenever there is any degree of irritation of
the stomach. The patient, or experimenter, should inspire a little,
however little, beyond the point which seems all that he can do, and
persist in this treatment every day. There can be no doubt but we
have here a most important aid in the treatment of consumption, not
only, but of all ill-conditions of the physical man. But the deep, full
breathing that comes from having exercised vigorously is best of all
(see page 84).

2 [NOTE ON BRIGHT’S DISEASE.]

How to Eat Meat.—In the chapter on this subject, I have taken


the position that Albuminuria results from: (1) excess in diet; (2) the
use of foods that can not, or are not properly masticated and
insalivated, as mush, or bread wet and washed down with any sort
of artificial fluids, gravy-drowned vegetables, etc.; (3) stimulating
drinks, as beer, spirits, tea, coffee, etc.; (4) excess of animal food.
To this I must add meat eaten in a manner totally different from that
in vogue with all carnivorous animals, viz.: hashed, or tender and
well chewed, instead of being, as it should be, swallowed in pieces
of convenient size—a rational modification in the premises, surely.
Dogs, wolves, cats, and the like, are gourmands, to be sure, but this
is not the fundamental reason for their manner of gulping their
natural food whole. It has been shown by experiments that dogs fed
on hashed meat suffer from indigestion, a portion of their food
passing undigested, while if fed the same quantity of meat in
chunks, no part of it appears in the excreta, but all is perfectly
digested.
Grain-eating animals teach us how to eat grain; or at least, how
to masticate farinaceous food. We may well learn from the carnivore
an analogous lesson—not, however, necessarily dispensing with knife
and fork, napkin or finger-bowl, nor any other improvement over
their primitive fashions!

THE POINT IS THAT FLESH-FOOD,

unlike starchy foods, requires stomach digestion only (as against


any change in the mouth), and only when taken in the natural
manner, that is, substantially as meat-eating animals take it, is it
retained in the stomach for a sufficient length of time to be dissolved
by the gastric juice; but much of it passes on into the intestine
prematurely (explaining, in great measure, the many cases of
inflammation of the bowels, as well as the frequent lesser
disturbances), and doubtless a considerable proportion is absorbed
in a more or less fermented state, adding thereby impure elements
to the blood, and predisposing the individual to inflammatory
disease. On the contrary, if meat is swallowed in pieces of moderate
size, each piece being acted upon at the surface gradually dissolves
from the outside, and so is perfectly changed by the gastric juice
before leaving the stomach. In personal experiments I find much
less inconvenience from eating flesh-food in this manner than results
when I treat it as we have always been taught to. It may be well to
caution against eating a large portion of meat in this manner at first;
it would give the stomach a new experience and likely enough create
disturbance. One-half the usual amount, taken naturally, would yield
as much nourishment as the full ration, perhaps; at any rate the
change should be made gradually (see pp. 50-158, for further
consideration of the animal food question). The following from the
Practitioner, corresponds (as far as M. Semmola carries the point)
with my view of the matter entirely, as regards the nature of the
malady. Albuminuria, or excess of albumen (that is, unappropriated
albuminoids in the circulation, and which are consequently excretory
matters), must necessarily result from any or all of the causes I have
named—causes of indigestion. Says the Practitioner:

“At a recent meeting of the Paris Academy of Medicine, M.


Semmola, of Naples (‘Progrès médical,’ June 9, 1883), brought
forward a new theory with regard to the causation of Bright’s
disease. This malady he regards as not essentially renal, but as
consisting in a general morbid alteration of nutrition, and observes
that albumen in such cases is not passed by the urine only, but by all
the secretory organs. This alteration [or, rather, I should say, the lack
of alteration by digestion] deprives the albuminoid materials of the
blood of their power of being assimilated, and so causes their
excretion by the emunctories. The renal lesions he ascribes to
mechanical irritation of the tubules of the kidney by the constant
passage of albumen through them. Albuminuria is therefore a cause,
not a result, of renal disease.[93] M. Simmola founds these views on
a series of experiments on animals. He injected into the blood-
vessels various substances containing albumen, as white of egg,
milk, and blood-serum, with the result of inducing artificial Bright’s
disease. White of egg was most active in this way.”
[93] And this only one of the hundred and one instances, in medical practice,
of “cart before the horse,” which may make the difference of life or death with
every patient under treatment!

3 [NOTE TO PAGE 169.]


Water As Medicine and Food.—There is no royal road to health
once deeply diseased. In certain cases, and for a limited period even
in these, hot water is invaluable. But if long continued—used as a
constant beverage instead of a temporary expedient to aid in
removing the slime and “gurry” from stomachs deeply coated[94]—
the effect will be to keep this organ weak, as a number of Turkish
baths every day would enfeeble, in time, the strongest man. One
valid objection to tea, chocolate, and coffee is, that they are usually
taken hot (see “Coffee, etc.”).
[94] Such patients require a more or less extended fast. This is always safe,
and in desperate cases the only means by which the necessary absorbing and
healing process can be assured (see pp. 62-71-73-169). The stomach of a healthy
creature is, when simply rinsed, absolutely clean and free from offensive matters;
but the constipated dyspeptic, or the consumptive, and many acutely diseased
persons, have stomachs which resemble that of an old, stall-fed ox, which has to
be scraped by the hour before the meanest tripe-eater would buy it, or place it
upon his table at any price. Yet a great deal of this kind of tripe is eaten by stall-
fed people every day. The flesh of healthy cattle finds no place in our markets nor
on our tables. Beef creatures are fed for fatness and tenderness, which is disease.

Warm water is about the most effectual remedy known to me


for acute dyspepsia. It should be drunk profusely, even to stomach
distension, with finger exploration, if necessary, to produce vomiting;
then a few cupfuls to retain, to wash away any residue of undigested
food, dilute the blood, etc. But cool, fresh water is the beverage par
excellence for all the year round (see pp. 76-90-100).

4 [NOTE ON “NATURAL DIET.”]

With regard to the suggestion, on page 211, of using milk to


wet farinaceous foods, in place of depending solely upon the natural
mouth-juices, I wish to say that it was felt by me, at the time, to be
entirely unphysiological, and by no means the best way to manage. I
now wish to urge that in so far as any one chooses to test the
advantages of this regimen he will not depart from a truly natural
way, so far as the natural way is possible; but rather use the whole
grain, or the whole meal dry, and take the milk (if indulged in at all)
by itself, and fruit likewise—after the grain. Several remarkable cases
have occurred since this book was first issued, in which the curative
powers of this diet have been displayed in a most marked manner. I
take occasion to mention one. Mrs. L., of Lee, N. H., had been
suffering for eight years, during which she had been able to walk but
little. She was growing worse, and finally was pronounced by her
physician incurably diseased with “ovarian tumor.” After six months’
use of uncooked food—a breakfast of fruit only, with dinner at night
composed of unsifted wheat meal (from one-third to one-half cupful,
at first, the amount increased later with increased exercise); dry,
followed with a little fruit—she is up and about the house, aiding in
the housework, and the past week did the entire family ironing. She
has been for eight years a great sufferer, but all her pains have been
banished, and her strength and general health are steadily improving
under a continuance of the diet as above described, together with
light, loose clothing, much fresh air, air-baths, self hand-rubbing, and
gradually increasing exercise from very small beginnings.

5 [NOTE TO PAGE 232.]

The Long-sought Principle.-It is confessedly a standing disgrace to


our profession that, after all the boasted “progress in medicine”
during these hundreds of years of research and experimentation, not
one great principle has been established by means of which the
people can be, even if disposed (and it can hardly be said that they
are, generally), guided toward perfect health. It is charged that
vegetarianism, even, has failed to speedily make sound, bright-eyed,
clear-skinned, healthy and therefore handsome men and women,
out of life-long “sinners” against the laws of life; and it must be
admitted that not all its promises are verified in practice, although it
seldom fails to greatly improve all who adopt the regimen (imperfect
as it is—and it is very imperfect) as practiced at the various hygienic
Cures at home and abroad. The trouble is that food-reformers have
only undertaken to modify, with half-way measures—to change a
very bad diet for one far from good, one form of “mush” for another
less harmful, but by no means physiological. I would assert here as
the one all-sufficient principle, so far as physical health is concerned,
looking to the rearing of children, that if we were to take a thousand
new-born infants—good, bad, and indifferent, as to inheritance—and
give them pure cow’s milk, avoiding the cramming that is universally
practiced; say, give them two full meals, or three moderate ones a
day (the quantity altogether gauged by the individual’s digestive
capacity); and, as they should arrive at suitable age (i. e., as teeth
began to develop), feed them on strictly natural food—the natural
diet—fruits, and grains (in winter, soaked twelve hours in little
water[95]), the fruit in large proportion; give them a chance to
develop normally, such as other young animals have—i.e., give them
freedom from holding, tending, baby-carting, and the like, except in
the smallest measure; dress them lightly, keep them free from foul
air, by sufficient ventilation of all living rooms; give them the utmost
freedom of the lawns or the ground—outdoor exercise—give them
this sort of treatment, and not five per cent. would die under five
years of age, nor, with fair regard for the known laws of life, would
many fail to reach old age in health. The at present supposably-
inevitable “diseases of infancy and childhood” could not exist. The
influence of the constant tending and holding to which all infants are
subjected is disastrous in a twofold degree: (1) for many months
they are prevented from taking much voluntary exercise, and (2) this
makes the involuntary cramming relatively more excessive; hence
they grow fat and disordered in every way, and predisposed to all
manner of sicknesses. Children scarcely ever have occasion to use
their teeth. The food in use requires no chewing. Little demand is
made upon the salivary glands (for food is hot, moist, and “goes
down itself”); hence these glands, which consequently fail to
develop normally, become at some time acutely diseased, or finally
almost if not entirely useless. Hollow, sunken cheeks result from this
cause. It was never designed to remedy this defect with fat. The
parotid glands and the cheek muscles should be developed and
maintained by physiological eating. The teeth for want of use fail, as
the muscular system declines through indolence. Unnatural food,
fast eating, overeating, poor teeth, dentists, “mumps,” plethora, and
febrile diseases, or chronic dyspepsia, and all manner of ailments—
this is the present order of things (see advertisement of “How to
Feed the Baby”).
[95] This treatment restores the flinty grain (wheat, rye, barley, maize, sweet
corn) to its natural plumpness and masticability. There should be little or no liquid
to turn off.

6. TIRED FROM INACTION: TOO MUCH “REST.”

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.

But the consumptive, the delicate person, who, as is the case


generally, has grown weaker and weaker from doing less and less
(and this is in accordance with natural law), becomes at last “tired”
in such a manner, that without an entire change—a right about face
—there is no such thing as getting rested this side the grave. This
exhaustion from indolence must be changed for the tiredness
resulting from physical exertion, or there is no hope of “cure.”
Friends must learn the error of their ways; they must cease the
eternal discouragement of the loved one; there must be no more of
the incessant, “Now, Jenny, sit right down—you will get too tired”;
“There, now, let me do that—you know how little it takes to tire
you”; “You are crazy to think of going outdoors such a day as this,”
etc., etc. (see page 85). However kindly meant all this is, it is, in
practice, “hitting a man when he is down”; while the usual
encouragement to eat (digestion or no digestion)—to eat (appetite
or no appetite—the inaction often forbidding all desire for food) is, to
use a sporting phrase, a companion “slugger” that finally knocks the
weakling off the stage. This is what produces the phlegm as fast as
the poor victim can cough it up. Because he has nothing to do—
because he does nothing—but ponder over his condition, eat,
manufacture phlegm and “raise” it, he lowers himself more and
more, until he gets to the bottom. He has “raised” about everything;
only the frame, the skeleton, is left to bury (see pp. 72, 78, 92, 97,
104).

A FEW OF THE MANY NOTES FROM READERS


OF THE FIRST
EDITION OF “NATURAL CURE.”

J. Russ, Jr., Haverhill, Mass., says: “Dr. Page’s explanation of the


‘colds’ question is alone worth the price of a hundred copies of the
book—it is, in fact, invaluable, going to the very root of the cause of
sickness.”
Mrs. W. O. Thompson, 71 Irving Place, Brooklyn, N. Y., says: “I
wish every friend I have could read it, and, only that hygienists
never harbor ill-feeling, that my enemies might not chance to find it.
I owe much to the truths made clear in ‘Natural Cure’; more, indeed,
than to all the health literature I have ever read (and I had read
much, because I had much need); and it is certain that my sister-in-
law owes her life and present robust health to the professional
attendance of its author.”

FROM A TEACHER.

Mrs. S. S. Gage, teacher in the Adelphi Academy, Brooklyn, N. Y.,


says: “My friend, Mrs. Thompson, recommended this book (‘Natural
Cure’) to me. Thanks to her and ‘the book,’ my old headaches
trouble me no more; I am cured of catarrh and partial deafness,
and, in fact, am better in every way. I never could accomplish so
much and with so little fatigue; and I am sure that all my intellectual
work is of better quality than it ever was before.”

FROM A HUSBAND.

D. Thompson, Lee, N. H., says: “Through following the advice in


‘Natural Cure’ my headaches, which have tortured me at frequent
intervals for forty years, return no more. Formerly I could not work
for three days at a time, now I work right along. For this, as well as
for the restoration of my wife to health, after we had given her up as
fatally sick, I have to thank Dr. Page and ‘The Natural Cure.’”

FROM THE WIFE.


Mrs. S. E. D. Thompson, Lee, N. H., says: “I can not well express
my gratitude for the benefit I have received from this book and the
author’s personal counsel. Condemned to die, I am now well. It is
truly wonderful how the power of resting is increased under the
influence of the regimen prescribed. I have distributed many copies
of this book, and have known of a life-long asthmatic cured,
biliousness removed, perennial hay fever banished for good, and
other wonderful changes produced, by means of the regimen
formulated in ‘Natural Cure.’ A friend remarked: ‘It is full of
encouragement for those who wish to live in clean bodies.’ Another
said: ‘It has proved to me that I have been committing slow suicide.’
Our minister says: ‘I have modified my diet and feel like a new
man.’”
To this Mrs. Thompson adds, for the author’s first book, “How to
Feed the Baby”: “I have known of a number of babes changed from
colicky, fretful children to happy well ones, making them a delight to
their parents, by following its advice.”

William C. Langley, Newport, R. I., says: “While all would be


benefited from reading it, I would especially commend it to those
who, from inherited feebleness, or who, like myself, had declined
deeply, feel the need of making the most of their limited powers. I
may add, that this work bears evidence that the author has had
wide range and extensive reading, together with a natural fitness for
physiological and hygienic research, keen perception of natural law
and tact in its application.”
Solomon Alexander, No. 252 East Fifty-second Street, New York,
says: “I have been greatly benefited by Dr. Page’s treatment for
inflammatory rheumatism and Bright’s disease, and am now steadily
improving under his direction.” July 27, 1883. (Now well, November,
1883.)
Mrs. Dr. Densmore, 130 West 44th Street, New York, says: “You
can judge of my opinion of ‘Natural Cure’ when I tell you that I am
buying it of the publishers by the dozen to distribute among my
patients.”
The Popular Science Monthly for September, 1883, says: “The
author gives several remarkable examples of wonderful cures which
he knows of having been effected by following the principles he lays
down—principles which may be followed with profit, and the
following of which may relieve many cases regarded as desperate;
and he has given the public a most valuable manual of hygiene.”
The Atlantic Monthly for August, 1883, says: “An effort at
impressing common-sense views of preserving and restoring health.”
Several hundreds of most flattering notices from secular and
religious journals, on file at the publishers’ office, indicate how this
work is being received by the public.

SPECIAL NOTE.

It is evident from the nature of the press notices of “The Natural


Cure,” that the prefatorial request has been very generally complied
with, and that not only have critics managed to obtain an
understanding of the author’s position as regards the only certain
means for physical improvement from low conditions, but they are
disposed to sustain him in that position. Here and there one,
however, as was to be expected, from ignorance of natural law, from
personal preferences or notions, from faith in the old way (which has
so long been on trial and so signally failed), has failed to
comprehend the matter. Diving into the middle of the book, selecting
some chapter or paragraph which forbids a consumptive or any frail
patient, while doing nothing, to eat like a woodchopper or a railroad
hand, and especially warns such from eating worse kinds of food
than the man of mighty strength who might, through the influence
of active outdoor pursuits, get rid of considerable coffee, pie, cakes,
pickles, etc., and (providing his diet included plenty of coarse food)
even thrive in spite of a good deal of such material (for we know
that many indoor loafers, even, are too tough to be speedily killed
by such a diet)—carping critics, we mean to say, selecting some
special paragraph have held the advice up as “too radical in theory.”
But no person of sound mind can read this book through with even a
fair degree of care, and not learn that its chief aim is to teach people
who are now starving, or who are at best poorly nutrified, and, next
to these, the well ones who mean to keep on the safe side, the way
to live in order to be well nourished and free from the pains, aches,
and sicknesses which cover the land with wrecks of human beings—
dying—who might better live in clean, sound, and easy bodies.
INDEX.

Advantages of Deep Breathing, 84, 111


Albuminuria (Bright’s Disease), 116
Animal Food, Injurious Effects of, 51, 60, 61
Animal Food Unnecessary, 50, 158
Stimulating, 160
Acute Stage in the Cure of Chronic Disease, 222
Appetite, Tempting the, Mischievous, 66, 157, 262, 267
Appetite and Insanity, 141, 144
Apoplexy, 149
Air-Baths, 166, 171, 172
and Dyspepsia, 168
Apples and Summer-Complaint, 193

Bad Blood, 180


Bacillus Theory, The, of Consumption, 80
Blood, Bad, 180
Bathing, 90, 98, 166, 171, 172
Bed, A word About the, 102
Bowels, Consumption of the, 81
Forced Movement of the, Unhygienic, 110
Baths, Sun, 175
Air, 166, 171, 172
Injurious Forms of, 172
Biliousness, 152
and “Rich” Food, 153
Bright’s Disease (Albuminuria), 116
Symptoms of, 125, 127, 130
Breathing, Deep, 84, 111, 137
Careless, 137
Open-mouth, 101
Difficult, how Relieved, 101
Beef-tea Fallacy, The, 60, 61, 254
Brain, Pumping away the Effete Matters from the, 137
Bran (Wheat Hulls) Under the Microscope, 187
Brain Workers and Stimulation, 252
Bears, Honey-loving, 263

Continence, Influence of Diet in the Matter of, 265


Continence for Consumption, Essentiality of, 105
Credulity and Ignorance, 22
Cold Air not necessarily Pure, 240
Colds, 35, 36, 37, 41, 45, 171, 218
Influence of Diet on, 40, 218
Natural Cure of, 41
the Name a Misnomer, 45
Franklin’s Idea of, 171
Absurdity of, 40, 41, 42
Clothing, Day, 120
Night, 103
Constipation, 65, 107, 248
at Child-birth, 107
Consumption, 28
Curability of, 29
Congestion of the Lungs, How Produced, 99
Congestion of the Lungs from Indigestion, 99
Cheerfulness, Importance of, 77, 98
Carpets and Health, 97
Consumption, Out-door Life Essential to the Cure of, 30, 48
Consumption, Dyspepsia the Parent of, 54
Consumption from Fatty Degeneration, 79
Constipation, when “Closed Bowels” are not, strictly speaking, 65,
107
Constipation from Deficient Diet, 112
Chilliness, How to Remove, 109
Controlling the Symptoms, Folly of the Theory of, 112
Cures, Some Natural, 75, 85, 114, 168, 175
Climate, A Cold, Influence on the Kidneys, 116, 117
Croup as a Symptom in Albuminuria, 128
Catarrh, 153
Specific Treatment for, Danger of, 130
Catarrh, Suppressed and Diabetes, 130
Caffeine allied to Quinine, 244
Coffee, 243
and Indigestion, 251
and Insomnia, 139
and Health, 255
a Diuretic, 251
Cleanliness and Insomnia, 138
Cooking Vegetables, some Hints about, 177
Cooking, Injurious Effects of, 207, 210
Cost of Living, 206
Cure, The Raw-Food, 217
Chronic Diseases usually the Result of Chronic Provocation, 147
Child-birth, Constipation at, Normal, 107
Cistern Water, Stagnant, How to Renovate, 212
Christmas Dinner, A “Natural”, 227
Change of Air at Home, 237
Cream, Unwholesomeness of, 231
Caffeine, Artificial, How Manufactured, 248
Coffee and Courage, 258
and Tea more Injurious than Beer, 261
Coffee and Alcohol, Physiological Effects of, Similar, 259
Conclusion, 270
Cramming the Sick, Mania for, 59, 66, 76, 146

Diet, The Natural, 207


Various Hints about, 88, 153
Abstemious, for Consumptives, 89, 90, 92
Diet, Prevailing, Unwholesome, 227
Excessive, Promotes Consumption, How, 81, 82, 83
Diet, Influence of, on Health, 48, 59, 66, 81, 88, 99, 112, 113, 122,
126
Diet, A Physiological, 197
and Virtue, 265
Diabetes from Suppressed Nasal Catarrh, 130
Diabetes, Treatment for, 130
Death, Sudden, Accounted for, 31, 32, 149
Death Penalty, The, Nature’s Commutation of, 147, 148
Disease, The Temper, 39
Hunger a, 39
Providence and, 8, 9, 17
Prevalence of, 9, 14
Exciting Causes of, 11, 12
Predisposing Causes of, 11, 12, 35, 40
Diseases Arising from Renal Disorder, 130
Dyspepsia, 168
Doctors, A Prescription for, 95
Dry Diet, Advantages of, 93
Degeneration, Fatty, 78, 79, 80, 148, 150
Digestive and Muscular Capacity Compared, 68, 230
Dysentery, A Hint Concerning, 113
Diathesis, The “Disease”, 132
Unimportance of the Question of, 132
Dyspepsia and Dreams, 133
Diphtheria a Phase of Albuminuria, 128
The Class of Persons most Subject to, 128
Diuretics, The Best of All, 124
Diuretic, Coffee a, 251
Diseases, The True Interpretation of, 133
Dyspeptics are Recruited, How, 157
Diarrhœa, Chronic, Cured with Watermelons, 192
Driven Cow’s Milk Unnatural, 212
Digestion, Primary, in the Mouth, 93

Eating Alone Sometimes Useful, 176


Eating at Bed-time for Sleeplessness, 144
Error, A Common, 113
Exercise, Passive, 113
Exercise, The True Problem About, 70
Exercise for Consumptives, 69
Exercise, 68, 89, 90, 109, 119
Expectorants, Natural, 89, 91, 105
Exercise, Lack of, How to Counteract, 195
Exercise After Eating, 201, 202

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

Gastric Juice, Proportion of, Secreted, 93


Gout, 131, 209
Gouty Habit, The, a Symptom of Bright’s Disease, 131
Guiteau’s Appetite, 144
Grape-Cure, The, 214
Guano and Coffee, 248
Gnawing Stomach a Disease, 39

Hogs, Experiments on, 82


Hay-fever, 153, 209
Health Easily Secured, 18
Robust, how Promoted, 85, 96
A Duty, 19, 27, 35
Relation of, to Morals, 7, 54, 265, 270
Health the Safeguard against Contagion, 10, 11, 12
Heart Disease, 149
How to Keep Well, 96
Hints and Aphorisms, 154
House-cleaning in the “Living Temple”, 155
Hulls, Wheat, Under the Microscope, 187
Hunger Disease, The, 201
Hot Air may still be Pure, 240
Heart, Palpitation of the, from Coffee-drinking, 244
Hot Water as a Medicine, 98, 100
Herb Drinks and Female Weakness, 251

Insomnia and Air-bath, 138


a Symptom only, 134
Ignorance and Credulity, 22, 23
Insomnia and Coffee, 137
Insomnia, 133
Indigestion a Phase of Rheumatism, 145
Indigestion a Cause of Congestion of the Lungs, 99
Indigestion from Excess in Diet, 93
Intemperance, How Propagated, 55, 56, 261
Insanity and Fasting, 140
Insane? Who Are and Who are Not, 134
Insane, The, Usually Ravenous Eaters, 141
Infants are “Loved” to Death, How, 16

Japanese, Muscular, how fed, 161

Kidney Disease Unknown at the Arctics, 116, 117


Koch’s Theory of Consumption, 80
Kitchen-Curse, The, 233

Laziness a Disease, 34, 58


Liver Complaint, 168
Livers, “Fossil”, 179
Liver, Mercury “to Clear Out” the, 180
Lungs, Congestion of, from Indigestion, 99
Long Faces to the Rear, in Sickness, 103
Long Life, How Promoted, 85

Milk not a Natural Food for Adults, 153


Morality and Digestion, 157
Malaria, 236, 241, 247
Model Meal, A, 226
Meals, Number of, for Health, 48, 62, 72, 197
Mercury, to “Clear Out” the Liver, 180
Milk Fever from Excessive Diet, 150
Muscular Japanese, How the, are fed, 161
Milk and Biliousness, 152
Milk, 65, 152, 212
Mastication, Importance of Thorough, 92, 93
Moral Torpor a Disease, 34
Medicine, Hot Water as a, 98, 100
Why the Nostrum-makers Thrive, 25, 26

Natural Diet, The, 207


Nature Defeated by “Treatment”, 258
Nightmare from Using Tobacco, 251
Neuralgia, A Hint Concerning, 153
Nervous Prostration, A Hint Concerning, 253
Normal Constipation, 107
Night-air Superstition, The, 48
Nutrition the Grand Factor in Prevention or Cure, 58
Nausea and Hot Water, 100

Open Windows for Consumptives, 89


for Sewer Gas, 236
Obesity, Natural Cure of, 148
One-meal System, The, 62, 197
Organs, How all the Vital, become Degenerated, 181
Passions, Influence of Diet upon the, 265
Passive Exercise for Consumptives, 99
Constipation, 109, 113
Piles, How, are Produced, 111
Premature Deaths, 16, 230
Pneumonia, 102
Poison, “One’s Meat Another’s”, 43
How Food becomes, 61, 246
Providence and Disease, 8, 9, 17
Practice, the Reform, Obstacles to, 66, 95
Physiology a Part of Theology, 34
Physic, Good Health the Best, 108
Bad Effects of, 107
Fruit the Best, 194
Pain, the Office of, Friendly, 134
Pure Air, Popular Ignorance Concerning, 237
Pure Air, How to Ensure it, 239
Physical Independence, 255
Prejudice, Popular, against Reform, 234
Purgative, Tobacco as a, 250
Purgative, Food as a, 113, 114, 194

Quinine and Caffeine Closely Allied, 244

Roman Fever, The Cause of, 236


Race Horses are Injured, How, 198
Reform, A Rational, 234
Reformed Practice, Obstacles to the, 22, 66, 95
Rest after Meals, 200, 202
Regimen, The Traditional, 121
Rheumatism, 145
A Phase of Indigestion, 145
Chronic, Treatment for, 147
Rich Food a Cause of Biliousness, 153
Supportive Treatment, The, 258
Salisbury Theory, The, of Consumption, 81
Saline Starvation, 177
Scorbutic (Scurvy) Condition Predisposes to Zymotic Diseases, 10
Sedentary Life, Effects of a, 78, 84
Scrofula, Something About, 175, 194, 229, 231
Sickness, The Absurdity of, 9
Scrofulous Humors, How Manufactured, 231
Self-cure, Mrs. E.’s Story of her own, 85
Sewer-gas, 236
Straining at Stool Injurious, 110
Stimulation of the Kidneys Unnatural, 126
Skin, The Adaptability of the Skin to Sudden Changes of
Temperature, 35
Sympathetic Nervous System, The, 31, 46
Starvation, Eating Sometimes Hastens, 72
Starvation, Saline, 177
Starvation Dyspeptic, 58, 66
Stomach, The, the most abused of all the Organs, 46
Sugar, Artificial, Injurious, 78
Stomach Baths, 100
Signs of Disordered, 57
Stomachs, Sensitive, and Wheat Hulls, 189
Sleeping Alone, 106
Sleep, Efforts to Induce, Self-defeating, 135, 136
Sun-Baths, 171
Sunday Headaches, Cause of the, 200
Symptoms, Controlling The (!), 112
Stimulation from Diphtheritic Poison, 258
Stimulation, The true Theory about, 257
Sleeplessness Cured by Late Eating, 144
an Analogue of Pain, 135
Sunstrokes, Cause of, 196
Sleep, Regular Hours for, Necessary, 135
Summer Tortures, How avoided, 195

Traditional Regimen, The, 121


Treatment, The “Supportive”, 258
Tobacco and Insomnia, 137
as a Purgative, 250
Treating in Eating, 156
Teeth, One Cause of Poor, 207, 249
Typhoid Subject, A, 15
Telegraph System, Wonders of the Human, 31, 46
Table, A Well-furnished, 79
Toothache, 153
Thirst, How to Prevent, 98, 100
Tongue, The Story Told by the, 63

Unnaturalness of the Prevailing Diet, 227, 265, 266

Variety in Food not desirable, 92, 213


Virtue, Influence of Diet on, 53, 265
Valance, Poor Thomas, 125
Vegetarian Diet and Quantity, 161
Vegetarians, Some Noted, 51, 161
Vegetarianism and Endurance, 162
Vegetable Food, 48, 51, 52, 72, 158, 161
Vegetables Spoiled by Cooking, How, 177
Vinegar Yeast in the Blood, a Cause of Consumption, 81, 82
Ventilation, 47, 48, 97, 236, 238, 239
Vickers, The Case of Mr., 75

Watermelons, A Stale Joke about, 191


for Bowel Troubles, 192
Water as a Medicine, 98, 100, 113, 190
Weakness from Hot Drinks, 251
White Flour, Concerning, 49
Worrying, Effects of, 85
Waves of Disease!, 9
Wheat-meal vs. “Entire Flour”, 184
JUST PUBLISHED.
THE MAN WONDERFUL

IN

THE HOUSE BEAUTIFUL.

AN ALLEGORY.

TEACHING THE PRINCIPLES OF PHYSIOLOGY AND HYGIENE, AND


THE EFFECTS
OF STIMULANTS AND NARCOTICS.

FOR HOME READING.

Also adapted as a Reader for High Schools, and as a Text-


book
for Grammar, Intermediate, and District Schools.

BY CHILION B. ALLEN, A.M., LL.B., M.D., AND MARY A. ALLEN, A.B.,


M.D.

Fully Illustrated, Extra Cloth, 12mo, Price $1.50.

A work almost as wonderful as the subject of which it treats.


The motive is to teach that the most beautiful, and, at the same
time, the most wonderful thing in nature is man; and no one can
read these chapters without feeling that the authors have
accomplished their task.
The book is an allegory in which the body is the “House
Beautiful,” and its inhabitant the “Man Wonderful.” The building
of the house is shown from foundation to roof, and then we are
taken through the different rooms, and their wonders and beauties
displayed to us, and all this time we are being taught—almost
without knowing it—Anatomy, Physiology, and Hygiene, with
practical applications and suggestions.

We are then introduced to the inhabitant of the house, “The Man


Wonderful,” and learn of his growth, development, and habits. We
also become acquainted with the guests whom he entertains, and
find that some of them are doubtful acquaintances, some bad, and
some decidedly wicked, while others are very good company. Under
this form we learn of food, drink, and the effects of narcotics and
stimulants.

The Table of Contents by Chapters has these striking subjects:

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.

In fact, the book is more wonderful than a fairy tale, more


intensely interesting than a romance, and more replete with valuable
truths than any book of the present day.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like