Welcome to Django for Beginners, a project-based approach to learning web development with the Django web framework. In this book, you will build and deploy 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 Django projects from scratch using current best practices.

Django is a free, open-source web framework written in Python. 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.

Prerequisites

Django for Beginners is written for Django 4.2 and Python 3.11. All code examples work with these versions. By the time you read this, newer versions of both Django and Python may be available. In general, you should always strive to be on the latest version of Django and Python. As both are mature technologies, any issues arising in the future will be relatively minor.

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. This books is also suitable for programmers with previous web development experience but new to Django. 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.

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 routine tasks in web development, including:

  • User authentication
  • Testing
  • 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 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 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.

Django remains under active development with a regular release schedule of monthly security/bug fixes and a major new release every eight 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.

And best of all, Django is 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 has incredible documentation, there need to be more beginner-friendly tutorials. The documentation assumes you already know what you want to do and provides relatively terse explanations aimed at intermediate-to-advanced developers; tutorials are typically more geared towards beginners and hold your hand through all the steps required. When I first learned Django years ago, I struggled to complete the official polls tutorial. I remember thinking, Why was this so hard?

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 depth, but not both. They choose the latter, and as a professional developer, I appreciate the decision, 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 can be.

What’s New in Django 4.2

The most recent version of Django, 4.2, was released in April 2023. It has official support for Python 3.8, 3.9, 3.10, and 3.11. The official Django website contains information on all prior releases and detailed 4.2 release notes.

One of the significant efforts for Django since 3.0 has been adding asynchronous support. Django 3.0 added ASGI (Asynchronous Server Gateway Interface), while Django 3.1 included asynchronous views, middleware, tests, and test client. Django 4.0 began making cache backends async-compatible, and Django 4.1 added both asynchronous handlers for class-based views and an asynchronous ORM interface. Django 4.2 supports Psycopg 3, a PostgreSQL database adapter for Python that includes async support. These iterative improvements are bringing Django closer and closer to full asynchronous functionality.

Django 4.2 is an LTS (Long Term Support) release meaning it will receive security updates for at least three years after its release. The previous LTS was Django 3.2, which ends support in April 2024. As with all major releases, there are many new improvements for the 4.2 release, including a light or dark color theme for the admin.

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 learn about the powerful command line, Git, text editors, and how to install the latest versions of Python and Django.

In Chapter 2, we build our first project, a minimal Hello, World app demonstrating how to set up new Django projects. Because establishing good software practices is vital, we’ll 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 minimal code. We also add our first tests and deploy the website to Fly.io. Using platform-as-a-service providers like Fly transforms deployment from a painful, time-consuming process into something that takes just a few mouse clicks.

We build our first database-backed project in Chapter 4, a Message Board app, and then deploy it in Chapter 5. 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, store a remote copy on GitHub, and deploy our website using a production database.

In Chapters 6-9, we’re ready for a Blog app that implements CRUD (Create-Read-Update-Delete) functionality. Using 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. Our deployment checklist will also grow longer as we add enhanced security to the process.

The remainder of the book is dedicated to building and deploying a robust Newspaper site. Chapter 10 demonstrates how to use a custom user model, a Django best practice rarely addressed in tutorials. Chapter 11 covers user authentication: login, logout, and signup. Chapter 12 adds Bootstrap for enhanced CSS styling, and Chapter 13 implements password reset and change via email. In Chapters 14-16, we add articles, comments, proper permissions, and authorizations. Finally, in Chapter 17 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 highly 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, which are denoted 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.

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, it is likely that you are 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 towards an answer is the only thing that separates them from junior programmers. There is some truth to this.

You can only trust some of what you read online, of course, and 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, 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!

Conclusion

In the next chapter you’ll learn how to properly set up your computer and create your first Django project. Let’s begin!

Continue on to Chapter 1: Initial Set Up.