Author: Daniel/Audrey Roy Greenfeld
Pub Date: 2015
Size: 10 Mb
We’ll introduce you to various tips, tricks, patterns, code snippets, and techniques that we’ve picked up over the years.
We have put thousands of hours into the third edition of the book, writing and revising its material to include significant improvements and new material based on feedback from previous editions.
What is everyone saying about Two Scoops of Django?
- I read the first edition cover to cover. The second one raises the bar again. It’s pedagogical, entertaining, and thoughtful. — Aymeric Augustin, Django core developer.
- Whether you’re a Django beginner or a seasoned veteran, I recommend you get this book, and read it cover to cover, and keep it near you for easy reference. –Ken Cochrane, Django developer since 2008
- A single read-through of Two Scoops of Django gave me so many lightbulbs and tips; I had to go back for a second helping. — Lynn Root, Spotify engineer, PSF Director, and PyLadies ambassador.
- Make sure you have your favorite project next to you while reading. You’ll be doing some rewriting. — Bryan Veloso, GitHubber, PyCon PH Keynote Speaker
- You know those lessons you learn when projects blow up in your face? This book contains several projects worth of such lessons. — Lennart Regebro, author of “Porting to Python 3”
- This book should prove to be an amazing resource for any new-to-Django developer that picks it up. — Kenneth Love, Creator of “Getting Started with Django”
- This is the book I wished had existed and I could have read when I started learning Django. — Barry Morrison, Linux systems engineer and Django developer
This Book Is Intended for Django 1.8 and Python 2.7.x/3.3.x
This book should work well with the Django 1.8 series, less so with Django 1.7, and so on. Even though we make no promises about functional compatibility, at least the general approaches from most of this book stand up over every post-1.0 version of Django.
As for the Python version, this book is tested on Python 2.7.x and Python 3.3.3+.
None of the content in this book, including our practices, the code examples, and the libraries referenced applies to Google App Engine (GAE). If you try to use this book as a reference for GAE development, you may run into problems.
Each Chapter Stands on Its Own
Unlike tutorial and walkthrough books where each chapter builds upon the previous chapter’s project, we’ve written this book in a way that each chapter intentionally stands by itself. We’ve done this in order to make it easy for you to reference chapters about speciŀc topics when needed while you’re working on a project.
A little attention to following standard coding style guidelines will go a long way. We highly recommend that you read this chapter, even though you may be tempted to skip it.
The Importance of Making Your Code Readable
Code is read more than it is written. An individual block of code takes moments to write, minutes or hours to debug, and can last forever without being touched again. It’s when you or someone else visits code written yesterday or ten years ago that having code written in a clear, consistent style becomes extremely useful. Understandable code frees mental bandwidth from having to puzzle out inconsistencies, making it easier to maintain and enhance projects of all sizes.
What this means is that you should go the extra mile to make your code as readable as possible:
- Avoid abbreviating variable names.
- Write out your function argument names.
- Document your classes and methods.
- Comment your code.
- Refactor repeated lines of code into reusable functions or methods.
- Keep functions and methods short. A good rule of thumb is that scrolling should not be necessary to read an entire function or method.
When you come back to your code after time away from it, you’ll have an easier time picking up where you left off.
Take those pesky abbreviated variable names, for example. When you see a variable called balance sheet decrease, it’s much easier to interpret in your mind than an abbreviated variable like…
Django Coding Style
This section covers both the official guidelines as well as unofficial but commonly-accepted Django conventions.
Consider the Django Coding Style Guidelines
It goes without saying that it’s a good idea to be aware of common Django style conventions. In fact, internally Django has its own set of style guidelines that extend PEP 8: 2scoops.co/1.8-coding-style
Additionally, while the following are not speciŀed in the official standards, they are common enough
in the Django community that you will probably want to follow them in your projects.
Use Underscores in URL Pattern Names Rather Than Dashes
We always try to use underscores (the “ ” character) over dashes. Ļis isn’t just more Pythonic, it’s friendlier to more IDEs and text editors. Note that we are referring to the name argument of url() here, not the actual URL typed into the browser.
Choose JS, HTML, and CSS Style Guides
This chapter covered our preferred coding style and explained why we prefer each technique. Even if you don’t follow the coding style that we use, please follow a consistent coding style. Projects with varying styles are much harder to maintain, slowing development and increasing the chances of developer mistakes.
The Optimal Django Environment Setup
This chapter describes what we consider the best local environment setup for intermediate and advanced developers working with Django.
Use the Same Database Engine Everywhere
A common developer pitfall is using SQLite3 for local development and PostgreSQL (or MySQL) in production. This section applies not only to the SQLite3/PostgreSQL scenario, but to any scenario where you’re using two different databases and expecting them to behave identically. Here are some of the issues we’ve encountered with using different database engines for development and production:
You Can’t Examine an Exact Copy of Production Data Locally
When your production database is different from your local development database, you can’t grab an exact copy of your production database to examine data locally. Sure, you can generate a SQL dump from production and import it into your local database, but that doesn’t mean that you have an exact copy after the export and import.
How to Lay Out Django Projects
Project layout is one of those areas where core Django developers have differing opinions about what they consider best practice. In this chapter, we present our approach, which is one of the most commonly-used ones.
Django 1.8’s Default Project Layout
Let’s examine the default project layout that gets created when you run startproject and startapp:
In this chapter, we covered our approach to basic Django project layout. We provided a detailed example to give you as much insight as possible into our practices.
Project layout is one of those areas of Django where practices differ widely from developer to developer and group to group. What works for a small team may not work for a large team with distributed resources. Whatever layout is chosen should be documented clearly.
Building REST APIs
Today’s internet is much more than HTML-powered websites. Developers need to support AJAX and native mobile apps. Having tools that support easy creation of JSON, YAML, XML, and other formats is important. By design, a Representational State Transfer (REST) Application Programming Interface (API) exposes application data to other concerns.
We’ll go over the other side of REST APIs in chapter 17, Consuming REST APIs.
PACKAGE TIP: Packages for Crafting APIs
- django-rest-framework builds off of Django CBVs, adding a wonderful browsable API feature. It has a lot of features, follows elegant patterns, and is great to work with. This library has the deŀnitive lead in functionality over other similar tools, providing powerful tools for building CBV and FBV powered REST APIs. As of the release of this book, it is the defacto Django tool for building APIs.
- django-tastypie is a mature API framework that implements its own class-based view system. It’s a feature-rich, mature, powerful, stable tool for creating APIs from Django models. It was created by Daniel Lindsley, the developer who started the djangohaystack project, the most commonly used Django search library.
- For super-quick, super-simple one-off REST API views django-braces (CBVs) and django-jsonview (FBVs) can prove really useful. The downside is that when you get into the full range of HTTP methods and more complex designs, they rapidly become a hindrance due to their lack of focus on building APIs.
Fundamentals of Basic REST API Design
The Hypertext Transfer Protocol (HTTP) is a protocol for distributing content that provides a set of methods to declare actions. By convention, REST APIs rely on these methods, so use the appropriate HTTP method for each type of action:
Security Best Practices
When it comes to security, Django has a pretty good record. Ļis is due to security tools provided by Django, solid documentation on the subject of security, and a thoughtful team of core developers who are extremely responsive to security issues. However, it’s up to individual Django developers such as ourselves to understand how to properly secure Django-powered applications.
This chapter contains a list of things helpful for securing your Django application. This list is by no means complete. Consider it a starting point.
Harden Your Servers
Search online for instructions and checklists for server hardening. Server hardening measures include but are not limited to things like changing your SSH port and disabling/removing unnecessary services.
Know Django’s Security Features
Django 1.8’s security features include:
- Cross-site scripting (XSS) protection.
- Cross-site request forgery (CSRF) protection.
- SQL injection protection.
- Clickjacking protection.
- Support for TLS/HTTPS/HSTS, including secure cookies.
- Secure password storage, using the PBKDF2 algorithm with a SHA256 hash by default.
- Automatic HTML escaping.
- An expat parser hardened against XML bomb attacks.
- Hardened JSON, YAML, and XML serialization/deserialization tools.
Most of Django’s security features “just work” out of the box without additional conŀguration, but there are certain things that you’ll need to conŀgure. We’ve highlighted some of these details in this chapter, but please make sure that you read the official Django documentation on security as well: docs.djangoproject.com/en/1.8/topics/security/