Professional Documents
Culture Documents
Full Chapter Two Scoops of Django 3 X Daniel Feldroy PDF
Full Chapter Two Scoops of Django 3 X Daniel Feldroy PDF
x Daniel
Feldroy
Visit to download the full and correct content document:
https://textbookfull.com/product/two-scoops-of-django-3-x-daniel-feldroy/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...
https://textbookfull.com/product/extrusion-bioprinting-of-
scaffolds-for-tissue-engineering-applications-daniel-x-b-chen/
https://textbookfull.com/product/beginning-django-web-
application-development-and-deployment-with-python-1st-edition-
daniel-rubio-auth/
https://textbookfull.com/product/django-for-professionals-
production-websites-with-python-django-william-s-vincent/
https://textbookfull.com/product/django-for-beginners-build-
websites-with-python-and-django-william-s-vincent/
Django Standalone Apps: Learn to Develop Reusable
Django Libraries 1st Edition Ben Lopatin
https://textbookfull.com/product/django-standalone-apps-learn-to-
develop-reusable-django-libraries-1st-edition-ben-lopatin/
https://textbookfull.com/product/code-for-opencv-3-x-with-python-
by-example-second-edition-gabriel-garrido/
https://textbookfull.com/product/lola-the-millionaires-part-two-
sweetverse-book-3-1st-edition-kathryn-moon/
https://textbookfull.com/product/tango-with-django-a-beginners-
guide-to-web-development-with-python-django-1-9-1st-edition-leif-
azzopardi/
https://textbookfull.com/product/django-the-easy-way-a-step-by-
step-guide-on-building-django-websites-3rd-edition-samuli-natri/
Prepared exclusively for LAKLAK LAKLAK (39r4ye7vy@relay.firefox.com) Transaction: 11322
Two Scoops of Django 3.x
Best Practices for the Django Web Frame-
work
Daniel Feldroy
Audrey Feldroy
Copyright © 2013-2020 Daniel Feldroy, Audrey Feldroy, and Two Scoops Press.
All rights reserved. This book may not be reproduced in any form, in whole or in part, without written permission
from the authors, except in the case of brief quotations embodied in articles or reviews.
Limit of Liability and Disclaimer of Warranty: The authors have used their best efforts in preparing this book,
and the information provided herein “as is.” The information provided is sold without warranty, either express or
implied. Neither the authors nor Cartwheel Web will be held liable for any damages to be caused either directly
or indirectly by the contents of this book.
Trademarks: Rather than indicating every occurrence of a trademarked name as such, this book uses the names
only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the
trademark.
The only authorized vendor or distributor for Two Scoops of Django are Feldroy, Inc and the vendors or distributors
listed on https://feld.to/authorized-vendors. Support this book by only purchasing or getting it from
https://feld.to/authorized-vendors.
feldroy.com/pages/malcolm-tredinnick-memorial
Daniel had worked with Malcolm Tredinnick in the summer of 2010, but we first met him
in person at DjangoCon 2010. He was funny and charming, sharply opinionated but always
a gentleman; we instantly became close friends.
In 2012, when we co-organized the first PyCon Philippines, as soon as we told him about
it, Malcolm instantly declared he was coming. He gave two memorable talks and ran an
impromptu all-day Django tutorial. He also pushed and encouraged the local community
to work on Filipino language translations for Django, including Tagalog, Tausug, Cebuano,
and more.
After the conference, we started working on a book about Django best practices. We gath-
ered friends and colleagues to help us as technical reviewers. Malcolm Tredinnick became
the most active of them. He was our mentor and forced us to dig deeper and work harder.
He did this while working a day job as the leader of a combined Rails and Haskell team;
Malcolm was a true programming language polyglot.
For our book, he provided so much assistance and guidance we tried to figure out a way
to include him in the author credits. When we told him about our dilemma, he laughed it
off saying, “For a book called ‘Two Scoops’, you can’t have three authors.” We suggested he
share credit with us on a second book, and he refused, saying he preferred to just comment
on our work. He said that he wanted people to have proper references, and for him, simply
reviewing our work was contributing to the greater good. Eventually the two of us quietly
planned to somehow coerce him into being a co-author on a future work.
After months of effort, we released the first iteration on January 17th, 2013. Malcolm
stepped back from Two Scoops of Django, but we stayed in touch. Since Malcolm was
unable to attend PyCon US 2013 we weren’t sure when we would meet him again.
We knew Malcolm for less than three years and yet he made an incredible difference in our
lives. We’ve heard many similar stories in the community about Malcolm; he was a friend
and mentor to countless others around the world. His last lesson to us went beyond code or
writing, he taught us to never take for granted friends, family, mentors, and teachers.
Dedication v
About the Dedication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi
Introduction xxix
A Word About Our Recommendations . . . . . . . . . . . . . . . . . . . . . xxix
Why Two Scoops of Django? . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx
Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
This Book Is Intended for Django 3.x and Python 3.8 or 3.9 . . . . . . . xxxi
Each Chapter Stands On Its Own . . . . . . . . . . . . . . . . . . . . . xxxi
Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
Core Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxii
Keep It Simple, Stupid . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxii
Fat Models, Utility Modules, Thin Views, Stupid Templates . . . . . . . xxxiii
Start With Django By Default . . . . . . . . . . . . . . . . . . . . . . . xxxiii
Be Familiar with Django’s Design Philosophies . . . . . . . . . . . . . . xxxiv
The Twelve-Factor App . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiv
Our Writing Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiv
Provide the Best Material . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiv
Stand on the Shoulders of Giants . . . . . . . . . . . . . . . . . . . . . . xxxiv
Listen to Our Readers and Reviewers . . . . . . . . . . . . . . . . . . . xxxv
Publish Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxv
1 Coding Style 1
1.1 The Importance of Making Your Code Readable . . . . . . . . . . . . . 1
1.2 PEP 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 The 79-Character Limit . . . . . . . . . . . . . . . . . . . . . . 3
3.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Acknowledgments 431
Index 441
The first edition of Two Scoops of Django came out in 2013 when Django was only on ver-
sion 1.5, and I was just beginning my own Django journey. I still recall the deep frustration
of trying to properly wrap my mind around this batteries-included web framework. I had
studied Python. Gone through the official Django Polls tutorial multiple times. And read
every book and tutorial I could find. But, still, I felt lost. Whenever it came time to build
my own Django apps from scratch, I hit a wall. Stack Overflow provided answers to discrete
questions, but no larger context of understanding. Open source Django code–what little of
it I could find, anyway–seemed hopelessly complex, far beyond my abilities as a budding
developer.
In short, I was stuck in the classic tutorial trap that afflicts so many beginners: able to blindly
follow along with Django tutorials, yet unable to truly understand what was happening.
And then I found this book. Here, finally, was an opinionated guide to using Django. One
that took a holistic approach to the framework and the process of building web applications.
At first, I was surprised by the format: it didn’t adopt the traditional step-by-step process
of walking through a demo Django application. The book didn’t build a complete website
at all. Instead, it was structured like an encyclopedia covering all the major areas of Django.
If I wanted to know the proper way to configure, say, my models, I could go to that section,
read the advice, and apply it in my projects.
While reading the book I spotted a few typos and gathered the courage to contact the
authors, Daniel and Audrey. To my surprise, they responded immediately, thanked me, and
several weeks later a signed and illustrated additional copy of the book arrived at my door.
I still have that book on my bookshelf.
This type of interaction, welcoming a newcomer into the fold, turns out to be quite common
in the Django community. It is perhaps the nicest technology group I know of, and many
Django developers feel the same way. There is a saying among those who have been around
Django for a while, “Come for the framework, stay for the community.” And it is true.
If you want to become involved, there are multiple ways. The codebase is open source so
anyone can submit a pull request. There are also annual DjangoCon conferences in the U.S.,
Europe, Australia, and Africa, as well as innumerable smaller local meetups and conferences.
As technology continues its relentless march onwards, Django and the broader Python com-
munity has kept pace. Since that first version of Two Scoops back in 2013, there have been
new editions covering Django 1.6, 1.8, and 1.11, all of which I bought, learning something
new and revisiting wise advice I’d read years before. The old debates of Python 2 vs Python
3 and related third-party package support are now settled, replaced by new ones, I suspect,
around the new async capabilities in Python that are making their way into Django.
To a newcomer, Django can feel intimidating: it certainly did for me. But thanks to the
community and resources like Two Scoops, it is more accessible than ever. I encourage you
to join us and, who knows, maybe even make your own contributions.
William Vincent
Django Software Foundation Board Member
Founder of LearnDjango.com
May 2020
I wanted to use Django for the front-end of the web service, but management insisted on
using a closed-source stack because “Django is only at version 0.9x, hence not ready for real
projects.” I disagreed, but stayed happy with the realization that at least the core architecture
was in Python. Django used to be edgy during those heady days, and it scared people.
Many years later, Django is considered a mature, powerful, secure, stable framework used by
incredibly successful corporations (OctopusEnergy, Instagram, Mozilla, Sentry, etc.) and
government agencies (NASA, Library of Congress, et al) all over the world. Convincing
management to use Django isn’t hard anymore, and if it is hard to convince them, finding
jobs which let you use Django has become much easier.
My goal in this book is to share with you what I’ve learned. My knowledge and experience
have been gathered from advice given by core developers, mistakes I’ve made, successes
shared with others, and an enormous amount of note taking. I’m going to admit that the
book is opinionated, but many of the leaders in the Django community use the same or
similar techniques.
This book is for you, the developers. I hope you enjoy it!
AN ARCTIC SNOW-STORM.
It was a terrible night. The wind blew a hurricane, and the snow
fell heavily in drifting, whirling masses. “We did not know,” says
Tyson, “who was on the ice, or who was on the ship;” but seeing
some musk-ox skins lying across a wide crack in the ice, he pulled
them towards him to save them—and behold, rolled up in one of
them were two or three of the children of Hans the Eskimo! Some of
the men were afloat on small pieces of ice, but by means of the
whale-boat these were rescued; and when the gray light of morning
dawned on the scene, Tyson ascertained that eighteen persons,
besides himself, were castaways. These were—Mr. Meyers,
meteorologist; Heron, steward; Jackson, cook; six seamen; Joe and
Hans, the Eskimos, and their wives and children.
The piece of the floe on which they were cast was nearly circular,
and about four miles in circumference. It was not level, but full of
hillocks, and of ponds or small lakes, which had been formed by the
melting of the ice during the short summer. The ice varied greatly in
thickness. Some of the mounds, or hills, were probably thirty feet
thick; the flat parts not more than ten or fifteen. The surface was
exceedingly rugged, and the hummocks were white with snow.
Tyson’s first task was to inspect the stock of provisions that had
been collected on the floe. It consisted of fourteen cans of
pemmican, eleven and a half bags of bread, one can of dried apples,
and fourteen hams; and if the ship did not return for them, they might
have to support themselves upon this supply all through the dreary
winter, or die of starvation. Fortunately, they had a couple of boats;
and Tyson’s second care was to load these, embark his little
company, and endeavour to reach the shore. In this attempt they
were balked by the drifting ice; and before they could repeat it they
caught sight of the Polaris. Immediately they ran up a rough and
ready signal; but no one seemed to be keeping a look-out, and the
castaways had the mortification of seeing her drop away behind
Littleton Island, without undertaking any search for her missing crew.
Tyson therefore resolved to cross to the other side of the floe,
and make for the land, perhaps lower down than the Polaris was, so
as to intercept her. Everything was thrown away, except two or three
days’ provisions, and the boats were got ready. But the men were
slow and reluctant; oars were wanting; a violent gale arose; and as
night was coming on, Tyson found himself compelled to abandon his
intention. On the following day, the ice again broke; and now the
adventurers were drifting with one boat on one piece of ice, while the
other boat, a part of their provisions, and an extemporized hut of
poles, remained on the main part of the original floe. The ice-raft
which carried Tyson and his companions measured about 150 yards
each way.
THE CASTAWAYS ON THE ICE.
ADRIFT ON THE ICE-FLOE.
On the 21st, however, the boat and provisions were recovered.
Joe, with the keen eye of an Eskimo, caught sight of the bow of the
boat, projecting from a fragment of the broken ice. Followed by his
faithful ally, Tyson went in search of it, leaping like a chamois-hunter
from crag to crag. Six of the dogs had accompanied him. These
were harnessed to the boat, and with the help of sturdy arms
dragged it over the disrupted floe. The whole party then removed to
the large floe, where some snow-houses were speedily erected.
They formed quite an encampment: one hut, or rather a sort of half-
hut, for Mr. Meyers and Captain Tyson; Joe’s hut for himself, his
wife, and their adopted daughter; a hut for the men; a store-house
for provisions, and a cook-house,—all united by arched galleries,
built of consolidated snow, with one main entrance, and smaller ones
branching off to the several apartments or huts. Hans built his igloë
separately, but close by. All were constructed after the Eskimo
fashion—that is, the ground being levelled off, one half of the floor
toward the end furthest from the entrance was slightly raised above
the other or front half. The raised part, as we have previously
explained, serves as parlour and bedroom; the lower area, as
workshop and kitchen. The walls and arched roof were built up of
square blocks of hard snow, packed hard and close by the force of
the wind. A square of about eighteen inches of this compressed
snow or ice served for window.
This good work done, Tyson took stock. Successive expeditions
had gathered together nearly all that was on the ice when the Polaris
drifted from them, and he found that their stores included two boats
—one of which, however, was being broken up for fuel—and one
kayack, a good supply of powder and shot, eleven and a half bags of
bread, fourteen cans of pemmican, fourteen hams, ten dozen cans
of meats and soups, one can of dried apples, and about twenty
pounds of chocolate and sugar mixed. The pemmican cases were
large, each weighing forty-five pounds; the meats and soups were
only one and two pound cans; the hams were small; the dried-apple
can counted for twenty-two pounds. Evidently, when divided among
nineteen people, this supply could not last many weeks; and unless
they reached the land, or could catch seals, starvation seemed their
probable ultimate fate. The allowance was reduced to eleven ounces
for each adult, and half that amount for the children,—rations
painfully inadequate to the proper support of the human frame in a
Polar region and during an Arctic winter.
RECOVERY OF THE BOAT BY CAPTAIN TYSON.
On the 23rd of October they lost sight of the sun. At this time they
were about eight or ten miles off-shore, and forty to fifty miles west of
Northumberland Island, in lat. 77° 30’ nearly. The Eskimos were on
the watch for seals day after day, but without success. In truth, it is
not easy to find the seal in winter, as they live principally under the
ice, and can be seen only when it cracks. A warm-blooded animal, it
cannot always remain beneath the frozen surface without breathing,
and for this purpose they make air-holes through the ice and snow.
These, however, are so small at the surface, not exceeding two and
a half inches across, that they are not easily distinguished, especially
in the twilight-gloom of an Arctic winter day.
The floe, or ice-raft, on which the crew of the Polaris had found
shelter, continued to drift slowly to the southward, impelled by wind
and current. The weather was so severe that it was worse than
useless to attempt to reach the shore. The castaways therefore
huddled themselves together in their igloes, or huts of snow, or took
such diversion as hunting for fox or seal afforded. Or when a gleam
of fair weather afforded an opportunity, Tyson took a short drive in
his sledge, and explored as much as he dared of the ice lying
towards the shore. On the 1st of November an attempt was made to
reach the land, the dogs being harnessed to the sledge, and the boat
loaded with the most essential articles; but the state of the ice
rendered all efforts of this kind fruitless.
DIFFICULT TRAVELLING.
The cold was now excessive,—35° below zero at noon, and 37°
at midnight. On the 13th, it sank below 40°. On the following day,
however, a strong westerly gale blew up; the cold became more
moderate—the temperature rose to -14°. Under the influence of the
gale, the ice began to crack and grind and break up; the natives
launched a kayack; a seal was hunted down, and the castaways
feasted gloriously. This, however, was but a transient gleam of good
fortune. On the 17th the glass again sank to 38°, and no more seals
were visible. The men were now reduced to less than twelve ounces
of food daily, which was not sufficient to furnish internal warmth, or to
strengthen the system against the terrible effects of the Arctic
climate.
The 19th was, to some extent, a day of hope; for, after an
absence of eighty-three days, the sun once more rose above the
misty horizon. Eskimo Joe took advantage of the burst of daylight to
undertake a hunting expedition. About five miles from the hut he
found open water, and shot two seals, but could land only one; the
young ice carried the other away. Encouraged by the cheerful glow
of the sun, he stayed out later than usual, and it was very dark
before he returned. A light of burning blubber was kindled to guide
him to the hut. It shone out upon the gloom of the night like a pharos.
THE GUIDING LIGHT.
The 25th of January marked the one hundred and third day of the
castaways’ voyage on the ice-raft, and they severely felt the
monotonous wretchedness of their existence. It was a beautiful day,
and perfectly calm; but the thermometer indicated 40° below zero. At
midnight the heavens were illuminated with all the glories of a
brilliant aurora. They seemed to be ablaze: from the south-west to
the north-east, from the horizon to the zenith, the magnetic fires shot
here and there, and wavered and undulated, like flame driven by a
strong wind. At one time the splendour was almost overpowering,
and the straining eye was fain to seek relief in darkness.
On the 1st of February a violent gale arose, blowing from the
north-west, and the ice, rolling and rocking beneath its influence,
split up into great cracks and fissures which threatened the safety of
the castaways. Huge blocks fell off from the floe; and the vast bergs
which had hitherto accompanied, and partly sheltered it, moved
rapidly before the wind. Everything acknowledged the might of the
storm; but as yet the adventurers had not been disturbed, though
surrounded by mountains of ice heavy enough, if driven against their
encampment, to have crushed them to atoms. Thus far they had
floated safely, but the position was one to cause reflection: at some
time or other the ice must break up, they knew; but whether they
would survive the catastrophe was beyond conjecture. They could
only wait and hope.
DRAGGING A SEAL.