Statistics
88
Views
2
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-11-22

AuthorWilliam S. Vincent

No description

Tags
django
Publisher: leanpub.com
Publish Year: 2025
Language: 英文
File Format: PDF
File Size: 19.9 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Django for Beginners (5th Edition) Build Modern Web Applications with Python William S. Vincent © 2018 - 2025 William S. Vincent
Table of Contents Foreword Chapter 0: Introduction Why Learn Django? Prerequisites What’s New in Django 5 Book Structure Book Layout Advice on Getting Stuck Community Conclusion Chapter 1: Initial Set Up The Command Line Shell Commands Install Python 3 on Windows Install Python 3 on Mac Python Interactive Mode Virtual Environments PyPI (Python Package Index) Install Django First Django Project The Development Server Text Editors VSCode Configurations Install Git Conclusion Chapter 2: Hello, World Website How the Internet Works How Web Frameworks Work Django Architecture Model-View-Controller vs Model-View-Template Initial Set Up Migrations
Create An App Your First View URL Dispatcher Git Conclusion Chapter 3: Personal Website Initial Set Up Homepage Function-Based View About Page Templates URL Dispatcher The Django Template Language Template Context Tests Git and GitHub Conclusion Chapter 4: Company Website Initial Set Up Project-Level Templates Function-Based View and URL Template Context, Tags, and Filters Class-Based Views and Generic Class-Based Views TemplateView get_context_data() Template Inheritance Named URLs Tests Git and GitHub Conclusion Chapter 5: Message Board Website Initial Set Up Databases Django’s ORM Database Model Activating Models
Django Admin Function-Based View Templates and URLs ListView Initial Commit Tests GitHub Conclusion Chapter 6: Blog Website Initial Set Up Blog Post Models Primary Keys and Foreign Keys Admin Views URLs Templates Static Files Individual Blog Pages get_absolute_url() Tests Git Conclusion Chapter 7: Forms ListView and DetailView Mixins CreateView UpdateView DeleteView Tests Conclusion Chapter 8: User Accounts Log In Updated Homepage Log Out Link Sign Up
Sign Up Link GitHub Conclusion Chapter 9: Newspaper Project Initial Set Up Git User Profile vs Custom User Model AbstractUser Forms Superuser Tests Git Conclusion Chapter 10: User Authentication Templates URLs Admin Tests Git Conclusion Chapter 11: Bootstrap Pages App Tests Testing Philosophy Bootstrap Signup Form Git and requirements.txt Conclusion Chapter 12: Password Change and Reset Password Change Customizing Password Change Password Reset Custom Templates Try It Out Git
Conclusion Chapter 13: Articles App Articles App URLs and Views Detail/Edit/Delete Create Page Additional Links Git Conclusion Chapter 14: Permissions and Authorization Improved CreateView Authorizations Mixins LoginRequiredMixin UpdateView and DeleteView Template Logic Git Conclusion Chapter 15: Comments Model Admin Template Comment Form Comment View Comment Template Comment Post View New Comment Link Git Conclusion Chapter 16: Deployment Hosting Options Web Servers and WSGI/ASGI Servers Deployment Checklist Static Files Middleware
Environment Variables DEBUG and ALLOWED_HOSTS SECRET_KEY, and CSRF_TRUSTED_ORIGINS DATABASES Gunicorn and Procfile requirements.txt Heroku Setup Deploy with Heroku Additional Security Steps Conclusion Chapter 17: Conclusion Learning Resources 3rd Party Packages Python Books Feedback
Foreword Django bills itself as “the web framework for perfectionists with deadlines,” an ode to its origins as a newspaper content management system (CMS) and its overriding approach of balancing features with practicality. From the beginning, Django was created for real-world developers who wanted a fast, elegant, and powerful way to build websites. It is hard to appreciate, almost twenty years after its first release, just how different the World Wide Web landscape is from back then. I first encountered Django in the early 2000s, shifting from a planned academic career to a self-taught web developer. Back then, Django wasn’t the Django we know today, with a vibrant community, regular community-run conferences, fantastic documentation, thousands of third-party packages, and all the rest. Instead, it was a plucky upstart released by early twenty-something kids from a Kansas newspaper. But it was immediately apparent that this was what I was looking for! For one thing, Django was written in Python rather than the PHP most web developers (myself included) used at the time. Python is a wonderfully readable, rich, and powerful programming language that has now won over much of the programming world, but at the time, it, too, was something of an upstart. Django also emphasized a “batteries-included” approach similar to Python, providing built-in solutions for most tasks while still allowing customization. As my work with Django deepened, I became a co-maintainer of Django REST Framework and several other packages in the ecosystem. In 2018, I eventually became a Django Fellow. The Fellowship program is a paid position sponsored by the Django Software Foundation, the non-profit that maintains Django. A Fellow works on Django, managing releases, reviewing pull requests, and doing all the unglamorous but necessary things for an open-source project to succeed. It was at a DjangoCon US event in 2018 that I first met the author of this book, Will Vincent. He gave a talk on Django API Authentication, and we started talking. We both agreed that a Django-focused podcast was needed and launched the first episode of Django Chat in early 2019; today, five years and 160+ episodes later, it is still going strong. During that time, Will was elected to the Board of the Django Software Foundation in 2020 and served as Treasurer for three years (2020-2023). Looking back now, we’re old hands, we’re veterans.
The first edition of this book came out in 2018 and immediately filled a void. As a Django Fellow, I was routinely asked for recommendations on how to learn Django, and Django for Beginners has long been my answer. It adopts Will’s typically patient approach in explaining how things work while including practical examples of how to quickly build Django websites. Although you start building a “Hello, World” app, by the end of the book, you’ve written multiple real-world Django projects from scratch, layering on new concepts and techniques each time. And don’t be fooled by the “Beginners” in the title; this book covers the fundamentals and essential areas such as testing, deployment, environment variables, security, and more. It is full of best-practice wisdom that jump-starts anyone wanting to learn more about Django, whatever their background. I am thrilled for you to embark on your journey with Django. As your guide, this book will open your eyes to the myriad ways Django can revolutionize your web development experience. I hope your journey is as rewarding for you as it has been for countless others. Django for Beginners is the perfect gateway to the framework, the ecosystem around it, and our wonderful community. Have fun, and welcome aboard! – Dr. Carlton Gibson Django Fellow (2018-2023) and core contributor / Co-maintainer Django REST Framework noumenal.es
Chapter 0: Introduction Welcome to Django for Beginners, a project-based approach to learning web development with Django, a free and open-source web framework written in Python. Django is used by everyone, from students and startup founders to the largest websites in the world, including Instagram, YouTube, Reddit, Netflix, Dropbox, and Spotify. Its “batteries-included” approach provides all the built-in functionality you need to create powerful, real-world web applications quickly, hence its tagline, “The web framework for perfectionists on a deadline.” Django’s abundance of features can feel overwhelming to newcomers. It doesn’t help that the official polls tutorial and the official documentation are targeted at intermediate-to-advanced level web developers, not beginners. The good news is that, as a “loosely coupled” framework, Django’s components work independently or together, allowing for a high degree of modularity. In other words, you only have to use (and learn) what you need. Even professional developers with years of experience will only utilize some of what the framework offers; it’s simply too big and too expansive for all its features to fit into a single project. You will find, though, that the same patterns and tasks arise in almost every Django website: create and structure a new project, connect to and query a database, add logic, perform CRUD (Create-Read-Update-Delete) operations, handle user accounts and forms, and so on. Django does not have to feel overwhelming; indeed, it shouldn’t! There is a built-in solution for almost every conceivable use case: that’s what the documentation is for! But no one, even the original creators and core developers who wrote much of the documentation, can keep it all in their heads. You shouldn’t attempt to either! This book started as my personal notes on building Django projects. It took a long time before I had internalized and felt comfortable with Django’s structure. The best way to solidify my understanding was to create progressively more complex projects focused on a new concept or skill. Eventually, I published my notes as a series of blog posts and, based on their popularity, created this book, now in its fifth edition.
In this book, you will learn how to build, test, and deploy six progressively more complex web applications. We will start with a “Hello, World” application and conclude with a real-world Newspaper website that ties together all the fundamental concepts and techniques covered in the book, including models, views, URLs, templates, forms, user accounts, permissions, and more. By the end of this book, you should feel confident creating Django projects from scratch and have the background to fill in any knowledge gaps with more advanced educational resources. Why Learn Django? Django was initially created in the fall of 2003 at the Lawrence Journal-World newspaper and named after the famous jazz guitarist Django Reinhardt; it was released as a free, open-source project in July 2005. That makes it almost twenty years old now, quite mature in software terms, but it has continued to thrive and is arguably more vibrant today than ever before. Each week, double-digit new code submissions are accepted into the framework, monthly security and bugfix releases, and a major new release every eight months. A vast ecosystem of third- party packages provides additional functionality beyond the core framework. Django is written in the wonderfully readable yet powerful Python programming language, arguably the most popular language in the world today. Python is the default choice in most undergraduate computer science curriculums, the dominant language for data science and artificial intelligence, and widely used in scientific research. Its ease of use and broad applicability make Python suitable for almost any task. Django inherited Python’s “batteries-included” approach and includes a wide range of built-in features for routine tasks in web development, including: ORM (Object-Relational Mapper): write Python rather than raw SQL for creating and querying database tables Authentication: a full-featured and secure system for user accounts, groups, permissions, and cookie-based user sessions Templating Engine: a simple syntax for adding variables and logic to create dynamic HTML Forms: a powerful form library that handles rendering and validation URL Routing: a clean, elegant URL schema that is easy to maintain and reason about
Admin Interface: a visual way to interact with all website data, including users and database tables Internationalization: multilingual support plus locale-specific formatting of dates, time, numbers, and time zones Security: protection against SQL injection, cross-site scripting, cross-site request forgery, clickjacking, and remote code execution This approach allows web developers to focus on what makes a web application unique rather than reinventing the wheel every time. Millions of users have already used and tested the necessary code, so you know it will be secure and performant. In contrast, some web frameworks like Flask adopt a microframework approach of providing only the bare minimum required for a simple webpage. Flask is far more lightweight than Django and allows maximum flexibility; however, this comes at a cost to the developer. Building a simple Flask website requires adding a dozen or more third-party packages, which may or may not be up-to-date, secure, or reliable. The lack of guardrails also means Flask’s project structure varies widely, which makes it difficult to maintain best practices when moving between different projects. Flask is a good choice for a web framework; it just has different strengths and weaknesses compared to a full-featured option like Django. There is a saying among long-time Django developers, “Come for the framework, stay for the community.” And it is true! Django has an unusually warm and welcoming community for all levels of programmer, represented in annual volunteer-run DjangoCon conferences across multiple continents, an active forum for discussion, and regular meetups in major cities. Unlike other open-source projects run by companies or individuals, Django is organized as a non-profit organization via the Django Software Foundation, whose goal is to promote, support, and advance the web framework. Its Board of Directors is voted on annually by the community. Millions of programmers have already used Django to build their websites, and millions more turn to it each year because it doesn’t make sense to reinvent the wheel when you can rely on a large community of brilliant developers who have already done the hard work for us. Prerequisites
You don’t need previous Python or web development experience to complete this book. Even someone new to programming and web development can follow along and feel the magic of writing web applications from scratch. However, familiarity with basic Python, HTML, and CSS will go a long way toward solidifying your understanding of core concepts. There are references throughout the book whenever Django differs from other web frameworks; the most obvious example is that Django adopts an MVT (Model-View-Template) approach slightly different from the dominant MVC (Model-View-Controller) pattern. We will cover these differences thoroughly once we start writing code. What’s New in Django 5 Django 5.0 was released in December 2023 and has official support for Python 3.10, 3.11, and 3.12. It’s important to note that Django’s versioning policy is time-based rather than feature-based. Roughly every eight months, a new feature release occurs, along with monthly bug fixes and security patches as needed. Django also follows the pattern of .0, .1, .2, and then back to .0 for feature releases, meaning you can expect Django 5.1 in August 2024, Django 5.2 in April 2025, Django 6.0 in December 2025, and so on. Django has such a large and active community of contributors that the decision was made years ago to focus on regular rollouts rather than wait for specific features to be completed. Specific releases (those that end in .2, like Django 5.2 and 6.2) are designated as long-term support (LTS) releases and receive security and data loss fixes applied for a guaranteed period, typically three years. This policy is designed for larger companies struggling to keep up with Django’s rapid release schedule. Still, the best security policy is to be on the latest possible release rather than an LTS version if you can. So, what’s new in Django 5.0? The most significant change is form field rendering, which is now greatly simplified. Facet filters were added to the admin to allow for easier UI filtering, database-computed default values are now possible, and there is official support for Python 3.10, 3.11, and 3.12. Django has gradually added asynchronous support over the years, and this release adds a new async function to the auth module that controls user authentication. But perhaps the most noticeable change for developers upgrading to the latest edition is that logout links must now be POST rather than GET requests.
Django is a mature web framework that strives to remain stable yet advance alongside the modern web. If you find yourself on a project with an older version of Django, there are detailed instructions for updating to the latest version. Book Structure The book begins by demonstrating how to configure a local development environment for Windows and macOS in Chapter 1. We then learn about the powerful command line, Git, configuring text editors, and how to install the latest versions of Python and Django. In Chapter 2, we review how websites and web frameworks work before diving into an overview of Django architecture. From there we build our first project, a minimal Hello, World website, while learning about views, URL, and apps. We even 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 Personal Website that introduces function-based views, templates, and the Django Templating Language. We explore the template context and write our first tests using Django’s built-in testing framework. Class-based views, template inheritance, and more advanced testing patterns are covered in Chapter 4, where we build a Company Website. This is the final project before we turn to Django models and database-backed websites. We build our first database-backed project in Chapter 5, a Message Board website. Django provides a powerful ORM (Object-Relational Mapper) that abstracts away the need to write raw SQL ourselves. Instead, we can write Python in a models.py file that the ORM automatically translates into the correct SQL for multiple database backends (PostgreSQL, MySQL, SQLite, MariaDB, and Oracle). We’ll explore the built-in admin app, which provides a graphical way to interact with data. Of course, we also write tests for all our code and store a remote copy on GitHub. In Chapters 6-8, we’re ready for a Blog website that implements CRUD (Create-Read-Update-Delete) functionality. Using first function-based views and then switching over to Django’s generic class-based views, we only have to
write a small amount of actual code for this. Then, we’ll add forms and integrate Django’s built-in user authentication system for signup, login, and logout functionality. The remainder of the book is dedicated to building and deploying a production- ready Newspaper website. Chapter 9 demonstrates setting up a new project using a custom user model and appropriate tests. Chapter 10 covers a complete user authentication flow of login, logout, and signup, while Chapter 11 adds Bootstrap for enhanced CSS styling. Chapter 12 implements password reset and change via email and in Chapters 13-15, we add articles, comments, proper permissions, and authorizations. Finally, in Chapter 16 production-ready deployment is covered. The Conclusion provides an overview of the central concepts introduced in the book and a list of recommended resources for further learning. While it may be tempting to skip around in this book, I recommend reading the chapters in order. Each chapter introduces a new concept and builds upon past teachings. By the end of this book, you’ll have a solid understanding of Django, the ability to build your apps, and the background required to fully take advantage of additional resources for learning intermediate and advanced Django techniques. Book Layout There are many code examples in this book styled as follows: Code # This is Python code print("Hello, World!") For brevity, we will use three dots, ..., when the existing code has not changed. The section of code that has changed is highlighted using a # new comment. Code def make_my_website: ... print("All done!") # new Advice on Getting Stuck
Getting stuck on an issue happens to every programmer at every level. The only thing that changes as you become more experienced in your career is the difficulty of tackling the question. Part of learning how to be a better developer is accepting this frustration, finding help, asking targeted questions, and determining when the best course of action is to step away from the computer and walk around the block to clear your head. The good news is that whatever error you are having, you are likely not the first! Copy and paste your error into a search engine like Google or DuckDuckGo; it will typically bring up something from StackOverflow or a personal blog detailing the same issue. Experienced programmers often joke that their ability to Google more quickly for an answer is the only thing that separates them from junior programmers. There is some truth to this. Of course, you can only trust some of what you read online. With experience, you will develop the context to see how the pieces of Django and code fit together. What do you do if you are stuck on something in this book? First, carefully check your code against what is in the book. If you’re still stuck, you can look at the official source code, which is available on GitHub. A common error is subtle white spacing differences that are almost impossible to detect to the naked eye. You can try copying and pasting the official source code if you suspect this might be the issue. The next step is to walk away from the computer or even sleep on the problem. It’s incredible what a small amount of rest and distance will do to your mind when solving problems. There are two fantastic online resources where the Django community gathers to ask and answer questions. The first is the official Django Forum, and the second is the Django Users Google Group. Each is an excellent 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-developers mailing list, the non-profit Django Software Foundation that oversees Django, annual DjangoCon conferences, and local meetups where developers gather to share knowledge and insights. Regardless of your level of technical expertise, becoming involved in Django is a great way to learn, meet other developers, and enhance your 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!
Chapter 1: Initial Set Up This chapter focuses on configuring your Windows or macOS computer to work on Django projects. You are probably eager to dive right in, but setting up your computer correctly now will save you a lot of pain and heartache later. You are probably eager to dive right in and start using Django, but configuring your computer now for Django development is a one-time task that will pay many dividends in the future. It is important to be comfortable with the command line and shell commands, understand how to use virtual environments, install the latest version of Python, use a text editor, and work with Git for version control. By the end of this chapter, you will have created your first Django project from scratch and be able to create and modify new Django projects with just a few keystrokes. The Command Line The command line is a text-only interface that harkens back to the original days of computing. 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. Regular computer users will never need to use the command line. Still, for software developers, it is a vital and regularly used tool necessary to execute programs, install software, use Git for version control, and connect to servers in the cloud. With practice, most developers find that the command line is 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, use the command line with caution. Refrain from mindlessly copying and posting commands you find online; rely only on trusted resources. In everyday usage, multiple terms 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, and the shell is the program that runs commands on the underlying operating system. 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. The built-in terminal and shell on Windows are both called PowerShell. To access it, locate the taskbar next to the Windows button on the bottom of the screen 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:\Windows\System32> Before the prompt is PS, which refers to PowerShell, the initial C directory of the Windows operating system, followed by the Windows directory and, within it, the System32 directory. Don’t worry about what comes to the left of the > prompt at this point: it varies depending on each computer and can be customized later. The shorter prompt of > will be used going forward for Windows. At this point, we need to navigate to the users directory, so enter the command cd \users followed by the Enter key to change directories (cd) into users. Shell PS C:\Windows\System32> cd \users PS C:\Users> On macOS, the built-in terminal is called Terminal. Open it via the Spotlight app: simultaneously press the Command and Space bar keys 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 Terminal application, which 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%