Book Image

Django Design Patterns and Best Practices

By : Arun Ravindran
Book Image

Django Design Patterns and Best Practices

By: Arun Ravindran

Overview of this book

Table of Contents (19 chapters)
Django Design Patterns and Best Practices
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Django is one of the most popular web frameworks in use 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 book attempts to share solutions to several common design problems faced by Django developers. Sometimes, there are several solutions but we often wonder whether there is a 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 1.7 comes loaded with exciting new features, such as built-in schema migrations and app reloading. Python 3.4 is the bleeding edge of the language with several new modules, such as asyncio. Both, 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.

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, its importance, and several popular pattern collections.

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

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

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 us how short and meaningful URLs are designed.

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

Chapter 6, Admin Interface, shows us 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 improving its default look and feel.

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

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

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

Chapter 10, Security, familiarizes you with various web security threats and their countermeasures, and especially with how Django can protect you. Finally, a handy security checklist reminds you of commonly overlooked areas.

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

Appendix, 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 then move on to the new modules and tools offered in Python 3.

What you need for 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 Python 2.7, after reading Appendix, Python 2 Versus Python 3) or later

  • Django 1.7 or later

  • 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. Here is a 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 as, say—the factory_boy package. In most cases, they can be installed using pip as follows:

$ pip install factory_boy

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

Who this book is for

This book is aimed at developers who want insights into building highly maintainable websites using Django. It will help you gain a deeper understanding of the framework, but it will also familiarize you with several web development concepts.

It will be useful for beginners and experienced Django developers alike. It assumes that you are familiar with Python and have completed a basic tutorial on Django (try the official polls tutorial or a video tutorial from http://arunrocks.com).

You do not have to be an expert in Django or Python. No prior knowledge of patterns is expected for reading this book. More specifically, this book is not about the classic Gang of Four patterns, though they might get mentioned.

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

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

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)

Any command-line (typically Unix) input or output is written as follows:

$ django-admin.py --version
1.6.1

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 case 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 the section named Patterns in this Book in Chapter 1, Django and Patterns.

Tips and best practices are styled in the following manner:

Tip

Best Practice

Change your super suit every 5 years.

New terms and important words are shown in bold.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Pull requests and bug reports to the SuperBook project can be sent to https://github.com/DjangoPatternsBook/superbook.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.