📄 Page
1
(This page has no text content)
📄 Page
2
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
📄 Page
3
Also ByWilliam S. Vincent Django for APIs Django for Professionals
📄 Page
4
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
📄 Page
5
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
📄 Page
6
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
📄 Page
7
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
📄 Page
8
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
📄 Page
9
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
📄 Page
10
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 simpleHello, World app, progressing to a Pages app, aMessage 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 powersmany 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 1https://djangoproject.com
📄 Page
11
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, someweb frameworks like Flask2 adopt amicroframework 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 amajor new release every 8months. 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 2https://flask.palletsprojects.com/en/2.0.x/ 3https://www.djangoproject.com/download/#supported-versions 4https://docs.djangoproject.com/en/4.0/intro/tutorial01/
📄 Page
12
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, theremay be newer versions of bothDjango 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 howDjango allows for DRY (Don’t Repeat Yourself) developmentwithHTML 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
📄 Page
13
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-15we 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:
📄 Page
14
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
📄 Page
15
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 resourceswhere theDjango 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! 5https://github.com/wsvincent/djangoforbeginners 6https://forum.djangoproject.com/ 7https://groups.google.com/g/django-users 8https://docs.djangoproject.com/en/dev/internals/mailing-lists/#django-developers-mailing-list 9https://www.djangoproject.com/foundation/
📄 Page
16
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 configureDjango projects. Thenwe 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 youwill have created your first Django project from scratch andmore 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
📄 Page
17
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.
📄 Page
18
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 forWindows (PowerShell) andmacOS are similar. For example, the command whoami returns the computer name/username onWindows 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. OnWindows and macOS the command pwd (print working directory) outputs the current location within the file system.
📄 Page
19
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. Tomake a new directory use the command mkdir followed by the name.Wewill create one called code on the Desktop and then within it a new directory called ch1-setup.
📄 Page
20
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 downmenu. Click on Profiles in the topmenu and then Shell from the list below. There is a radio button for “When the shell exits:”. Select “Close the window.”