Book Image

Django Design Patterns and Best Practices - Second Edition

By : Arun Ravindran
Book Image

Django Design Patterns and Best Practices - Second Edition

By: Arun Ravindran

Overview of this book

Building secure and maintainable web applications requires comprehensive knowledge. The second edition of this book not only sheds light on Django, but also encapsulates years of experience in the form of design patterns and best practices. Rather than sticking to GoF design patterns, the book looks at higher-level patterns. Using the latest version of Django and Python, you’ll learn about Channels and asyncio while building a solid conceptual background. The book compares design choices to help you make everyday decisions faster in a rapidly changing environment. You’ll first learn about various architectural patterns, many of which are used to build Django. You’ll start with building a fun superhero project by gathering the requirements, creating mockups, and setting up the project. Through project-guided examples, you’ll explore the Model, View, templates, workflows, and code reusability techniques. In addition to this, you’ll learn practical Python coding techniques in Django that’ll enable you to tackle problems related to complex topics such as legacy coding, data modeling, and code reusability. You’ll discover API design principles and best practices, and understand the need for asynchronous workflows. During this journey, you’ll study popular Python code testing techniques in Django, various web security threats and their countermeasures, and the monitoring and performance of your application.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
PacktPub.com
Contributors
Preface
Index

Preface

Django is one of the most popular web frameworks today. It powers large websites such as Pinterest, Instagram, Disqus, and NASA. With a few lines of code, you can rapidly build a functional and secure website that can scale to millions of users.

This is not a book about Gang of Four design patterns.

Instead, it explains solutions to several common design problems faced by Django developers. Sometimes there are several solutions, but we tend to seek recommended approach. Experienced developers frequently use certain idioms, while deliberately avoiding certain others.

This book is a collection of such patterns and insights. It is organized into chapters each covering a key area of the framework, such as models, or an aspect of web development, such as debugging. The focus is on building clean, modular, and more maintainable code.

Every attempt has been made to present up-to-date information and use the latest versions. Django 2.0 comes loaded with exciting new features, such as its simplified URL syntax, and Python 3.6 is the bleeding edge of the language with several new modules, such as asyncio, both of which have been used here.

Superheroes are a constant theme throughout the book. Most of the code examples are about building SuperBook, a social network of superheroes. As a novel way to present the challenges of a web development project, an exciting fictional narrative has been woven into each chapter in the form of story boxes.

Who this book is for

This book is aimed at developers who want insights on building highly maintainable websites using Django. It helps you gain a deeper understanding of not just the framework but also familiarizes you with several web development concepts.

It will be useful for beginners and experienced Django developers alike. It assumes that you are fluent in Python and have completed a basic tutorial on Django (try the official polls tutorial or a video tutorial from my website—arunrocks.com).

You do not have to be an expert in Django or Python. No prior knowledge of patterns is expected, but it would be helpful. Once again, this book is not about the classic Gang of Four patterns.

A lot of practical advice here might not be unique to just Django, but to most kinds of web development. By the end of this book, you should be a more efficient and pragmatic web developer.

What this book covers

Chapter 1, Django and Patterns, helps us understand Django better by telling us why it was created and how it has evolved over time. Then, it introduces design patterns, their importance, and several popular pattern collections.

Chapter 2, Application Design, guides us through the early stages of an application's life cycle, such as gathering requirements and creating mock-ups. We will also see how to break your project into modular apps through our running example—SuperBook.

Chapter 3, Models, gives us insights into how models can be graphically represented, structured using several kinds of patterns and can be later altered using migrations.

Chapter 4, Views and URLs, shows us how function-based views evolved into class-based views with the powerful mixin concept, familiarizes us with useful view patterns, and teaches how short and meaningful URLs are designed.

Chapter 5, Templates, walks us through Django template language constructs, explaining its design choices, suggests how to organize template files, introduces handy template patterns, and points to several ways Bootstrap can be integrated and customized.

Chapter 6, Admin Interface, focuses on how to use Django's brilliant out-of-the box admin interface more effectively and several ways to customize it, from enhancing the models to toggling feature flags.

Chapter 7, Forms, illustrates the often confusing form workflow, different ways of rendering forms, improving a form's appearance using crispy forms, and various applied form patterns.

Chapter 8, Working Asynchronously, tours various asynchronous solutions for the Django developer, from the feature-rich Celery task queues, Python 3's asyncio, to the brand new Channels, and compares them for you.

Chapter 9, Creating APIs, explains RESTful API design concepts with practical advice on topics such as versioning, error handling, and design patterns using the Django REST framework.

Chapter 10, Dealing with Legacy Code, tackles common issues with legacy Django projects, such as identifying the right version, locating the files, where to start reading a large code base, and how to enhance it to add new functionality.

Chapter 11, Testing and Debugging, gives us an overview of various testing and debugging tools and techniques, introducing test-driven development, mocking, logging, and debuggers.

Chapter 12, Security, familiarizes you with various web security threats and their counter measures, specifically looking at how Django can protect you. Finally, a handy security checklist reminds you of the commonly overlooked areas.

Chapter 13, Production-Ready, is a crash course in deploying a public-facing application beginning with choosing your webstack, understanding hosting options, and walking through a typical deployment process. We go into the details of monitoring and performance at this stage.

Appendix A, Python 2 Versus Python 3, introduces Python 3 to Python 2 developers. Starting off by showing the most relevant differences while working in Django, we move on to the new modules and tools offered in Python 3.

To get the most out of this book

You will just need a computer (PC or Mac) and internet connectivity to start with. Then, ensure that the following are installed:

  • Python 3.4 or later
  • Django 2 or later (will be covered in installation instructions)
  • Text Editor (or a Python IDE)
  • Web browser (the latest version, please)

I recommend working on a Linux-based system such as Ubuntu or Arch Linux. If you are on Windows, you can work on a Linux virtual machine using Vagrant or VirtualBox. Full disclosure, I prefer command-line interfaces, Emacs, and eggs sunny side up.

Certain chapters might also require installing certain Python libraries or Django packages. They will be mentioned like this—the factory_boy package. They can be installed using pip like this:

$ pip install factory_boy

Hence, it is highly recommended that you first create a separate virtual environment, as mentioned in Chapter 2, Application Design.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com
  2. Select the SUPPORT tab
  3. Click on Code Downloads & Errata
  4. Enter the name of the book in the Search box and follow the onscreen instructions

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Django-Design-Patterns-and-Best-Practices-Second-Edition and https://github.com/DjangoPatternsBook/superbook2. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/DjangoDesignPatternsandBestPracticesSecondEdition_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code words in text, folder names, filenames, package names and user input are shown as follows: "The HttpResponse object gets rendered into a string."

A block of code is set as follows:

from django.db import models
class SuperHero(models.Model):
    name = models.CharField(max_length=100)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

name = request.GET['user'] 

sql = "SELECT email FROM users WHERE username = '{}';".format(name) 

Any command-line input or output is written as follows:

$ django-admin.py --version
1.6.1

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "When the test harness fails with an error, such as Expected output X but got Y, you will change your test to expect Y."

Lines beginning with the dollar prompt ($ sign) are to be input at the shell (but skip the prompt itself). Remaining lines are the system output which might get trimmed using ellipsis () if it gets really long.

Each chapter (except the first) will have a story box styled as follows:

Note

SuperBook Chapter Title

It was a dark and stormy night; silhouettes of the caped crusaders moved within the charred ruins of the vast Ricksonian Digital Library for Medieval Dark Arts. Picking up what looked like the half-melted shrapnel of a hard disk; Captain Obvious gritted his teeth and shouted, “We need backup!”

Story boxes are best read sequentially to follow the linear narrative.

Patterns described in this book are written in the format mentioned in section named Patterns in this book in Chapter 1, Django and Patterns.

Tips and best practices are styled in the following manner:

Note

Best Practice:

Change your super suit every five years.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.