Introduction
Course Contents
- Changelog
- Foreword
- Introduction
- Chapter 1: Initial Set Up
- Chapter 2: Hello, World Website
- Chapter 3: Personal Website
- Chapter 4: Company Website
- Chapter 5: Message Board Website
- Chapter 6: Blog Website
- Chapter 7: Forms
- Chapter 8: User Accounts
- Chapter 9: Newspaper Project
- Chapter 10: User Authentication
- Chapter 11: Bootstrap
- Chapter 12: Password Change and Reset
- Chapter 13: Articles App
- Chapter 14: Permissions and Authorization
- Chapter 15: Comments
- Chapter 16: Deployment
- Chapter 17: Conclusion
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:
# 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.
{title="Code",lang="python"}
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!