Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: Introduction to the Django Framework
Django Framework Design Principles
Don’t Repeat Yourself (DRY) Principle
Explicit Is Better Than Implicit
Loosely Coupled Architecture
Install Django
Install Python (Prerequisite)
Update or Install pip Package Manager (Prerequisite)
Install virtualenv (Optional Prerequisite)
Install Django
Install Django from Git
Start a Django Project
Set Up a Database for a Django Project
Install Python Database Packages
Test Django Database Connection and Build Django Base Tables
Set Up Content: Understand Urls, Templates, and Apps
Create and Configure Django Urls
Create and Configure Django Templates
Create and Configure Django Apps
Set Up the Django admin Site
Configure and Install the Django admin site App
Configure and Install the Django admin site docs App
Chapter 2: Django Urls and Views
Url Regular Expressions
Precedence Rule: Granular Urls First, Broad Urls Last
Exact Url Patterns: Forgoing Broad Matching
Common Url Patterns
Url Parameters, Extra Options, and Query Strings
Url Consolidation and Modularization
Url Naming and Namespaces
View Method Requests
View Method Responses
Response Options for HTTP Status and Content-Type Headers
Built-In Response Shortcuts and Templates for Common HTTP Status: 404 (Not Found), 500 (Internal Server Error), 400 (Bad Request), and 403 (Forbidden)
Built-In Response Shortcuts for Inline and Streamed Content
View Method Middleware
Built-In Middleware Classes
Middleware Structure and Execution Process
Middleware Flash Messages in View Methods
Add Flash Messages
Access Flash Messages
Class-Based Views
Built-In Class-Based Views
Class-Based View Structure and Execution
Chapter 3: Django Templates
Django Template Syntax
Auto-Escaping: HTML and Erring on the Safe Side
Django Template Configuration
Template Search Paths
Invalid Template Variables
Debug Output
Auto-Escape
File charset
Automatic Access to Custom Template tag/filter Modules
Template Loaders
Create Reusable Templates
Built-In Context Processors
Django debug context processor (django.template.context_processors.debug)
Django request context processor (django.template.context_processors.request)
Django auth context processor (django.contrib.auth.context_processors.auth)
Django messages context processor (django.contrib.messages.context_processors.messages)
Other Built-In Django Context Processors: i18n, media, static, tz, and CSRF context Processors
Django i18n context processor (django.template.context_processors.i18n)
Django media context processor (django.template.context_processors.media)
Django static context processor (django.template.context_processors.static)
Django tz context processor (django.template.context_processors.tz)
Django CSRF context Processor (django.template.context_processors.csrf)
Custom Context Processors
Built-In Django Filters
Dates
Strings, Lists, and Numbers
Numbers
Strings
Lists and Dictionaries
Spacing and Special Characters
Development and Testing
Urls
Built-In Django Tags
Dates
Forms
Comparison Operations
Loops
Python and Filter Operations
Spacing and Special Characters
Template Structures
Development and Testing
Urls
Custom Filters
Structure
Options: Naming, HTML, and What Comes In and Out
Installation and Access
Chapter 4: Jinja Templates in Django
Jinja Advantages and Disadvantages
Transition to Jinja Templates from Django Templates
What Works the Same Way in Jinja and Django Templates
Variables and blocks
Conditionals and loops
Comments
Spacing and special characters
What Works Differently in Jinja Templates Compared to Django Templates
Filters
Context processors
No date elements like the {% now %} tag and filters like time and timesince
{% comment %} tag not supported
{% load %} tag not supported
Use {{super()}} instead of {{block.super}}
{% csrf_token %} tag not supported, instead use csrf_input or csrf_token variables
{% for %} loop variables
{% empty %} tag not supported in loops, use the {% else %} tag
{% groupby %} tag not supported, use the groupby filter
{% cycle %} tag not supported, use the cycler function or the loop.cycle variable in {% for %} loops
{% lorem %} tag not supported, use the lipsum Function
Other miscellaneous tags like {% static %}, {% trans %}, {% blocktrans %}, and {% url %} not supported
New Concepts and Features in Jinja Templates vs. Django Templates
More useful built-in filters, tests, and more resemblance to a Python environment
Global functions
Flexible tag nesting, conditionals, and references
Macros
Flexible variable assignment in templates with less restrictive scope
Line statements
Jinja Template Configuration in Django
Template Search Paths
Auto-Escaping Behavior
Auto-Reload Template Behavior and Caching
Invalid Template Variables
Template Loaders
Create Reusable Jinja Templates
Jinja Globals: Access Data on All Jinja Templates, Like Django Context Processors
Jinja Built-In Statements/Tags and Functions (Like Django Template Tags)
Comparison Operations
Loops
Python and Filter Operations
Spacing and Special Characters
Template Structures
Jinja Built-In Filters and Tests (Like Django Filters)
Strings, Lists, Dictionaries, Numbers, and Objects
Strings and Lists
Dictionaries and Objects
Strings
Numbers
Spacing and Special Characters
Development and Testing
Urls
Custom Filters and Tests in Jinja
Structure
Installation and Access
Jinja Extensions
Enable Jinja Extensions
Create Jinja Extensions
Jinja Policies
Chapter 5: Django Application Management
Django settings.py for the Real World
Switch DEBUG to False
Define ALLOWED_HOSTS
Be Careful with the SECRET_KEY Value
Define Administrators for ADMINS and MANAGERS
Use Dynamic Absolute Paths
Use Multiple Environments or Configuration Files for Django
Option 1) Multiple environments in the same settings.py file with a control variable
Option 2) Multiple environment files using configparser
Option 3) Multiple settings.py files with different names for each environment
Set Up Static Web Page Resources - Images, CSS, JavaScript
Set Up Static Resources in a Development Environment (DEBUG=False)
Access Static Resources in Django Templates
Access Static Resources in Jinja Templates
Set Up Static Resources in a Production Environment (DEBUG=True)
Django Logging
Python Core Logging Concepts
Django Default Logging
Create Log Messages
Custom Logging
Disable default Django logging configuration
Logging formatters: Message output
Logging handlers: Locations, classes, filters, and logging thresholds
Logging loggers: Python packages to use logging
Disable email to ADMINS on errors
Logging with Sentry
Set up Sentry the application
Set up a Django application to use Sentry
Django Email Service
Set Up a Default Connection to an Email Server
Set Up a Default Connection to Third-Party Email Providers
Email with Google Gmail/Google Apps
Email with Amazon Simple Email Service (SES)
Email with SparkPost
Built-In Helpers to Send Email
Custom Email: Attachments, Headers, CC, BCC, and More with EmailMessage
Debug Django Applications
Django Shell: Python manage.py Shell
Django Debug Toolbar
Django pdb
Django Extensions
Django Management Commands
Custom Management Command Structure
Custom Management Command Installation
Management Command Automation
Chapter 6: Django Forms
Django Form Structure and Workflow
Functional Web Form Syntax for Django Forms
Django View Method to Process Form (POST Handling)
CSRF: What Is It and How Does It Work with Django?
Django Form Processing: Initialization, Field Access, Validation, and Error Handling
Initialize Forms: Initial for Fields and Forms, __init__ method, label_suffix, auto_id, field_order, and use_required_attribute
Accessing Form Values: request.POST and cleaned_data
Validating Form Values: is_valid(), validators, clean_(), and clean()
Error Form Values: Errors
Django Form Field Types: Widgets, Options, and Validations
The Relationship between Widgets and Form Fields
Empty, Default, and Predetermined Values: Required, Initial, and Choices
Limiting Text Values: max_length, min_length, strip, and Validators
Limiting Number Values: max_value, min_value, max_digits, decimal_places, and Validators
Error Messages: error_messages
Field Layout Values: label, label_suffix, help_text
Set Up the Layout for Django Forms in Templates
Output Form Fields: form.as_table, form.as_p, form.as_ul, and Granularly by Field
Output Field Order: field_order and order_fields
Output CSS Classes, Styles, and Field Attributes: error_css_class, required_css_class, Widget, Customization, and Various Form Field Options
Output Form Field Errors: form..errors, form.errors, form.non_field_errors
Django Custom Form Fields and Widgets
Create Custom Form Fields
Customize Built-In Widgets
Create Custom Form Widgets
Custom Form Widget Configuration Options
Django Advanced Form Processing: Partial Forms, AJAX, and Files
Partial Forms
AJAX Form Submission
Files in Forms
Django Formsets
Formset Factory
Formset Management Form and Formset Processing
Formset Custom Validation and Formset Errors
Chapter 7: Django Models
Django Models and the Migrations Workflow
Create Django Models
Migrations and the Django Model Workflow
Django Model Data Types
Limiting Values: max_length, min_value, max_value, max_digits, and decimal_places
Empty, Null and Not Null Values: Blank and Null
Predetermined Values: default, auto_now, auto_now_add, and choices
Unique values: unique, unique_for_date, unique_for_month and unique_for_year
Form Values: Editable, help_text, verbose_name, and error_messages
Database Definition Language (DDL) Values: db_column, db_index, db_tablespace, primary_key
Built-In and Custom Validators: Validators
Django Model Default and Custom Behaviors
Model Methods
save() method
delete() method
Validation methods: clean_fields(), clean(), validate_unique() and full_clean()
Data loading methods: Refresh_from_db(), from_db(), and get_deferred_fields() methods
Custom methods
Model Manager Field: Objects
Model Meta Class and Options
Database Definition Language (DDL) table options: db_table, db_tablespace, managed, required_db_vendor, required_db_features and unique_together
Database Definition Language (DDL) index options: Indexes and index_together
Naming convention options: verbose_name, verbose_name_plural, label, label_lower, and app_label
Inheritance Meta options: Abstract and proxy
Query Meta options: Ordering, order_with_respect_to, get_latest_by, default_manager_name, base_manager_name, default_related_name, and select_on_save
Permission Meta options: default_permissions and permissions
Relationships in Django Models
One to Many Relationships in Django Models
Many to Many Relationships in Django Models
One to One Relationships in Django Models
Options for Relationship Model Data Types
Data integrity options: on_delete
Reference options: Self, literal strings, and parent_link
Reverse relationships: related_name, related_query_name, and symmetrical
Database options: to_field, db_constraint, swappable, through, through_fields, and db_table
Form values: limit_choices_to
Django Model Transactions
Transaction per Request: ATOMIC_REQUESTS and Decorators
Context Manager and Callbacks: atomic() and on_commit()
Django Model Migrations
Migration File Creation
Migration File Renaming
Migration File Squashing
Migration File Structure
Migration File Rollback
Django Model Database Tasks
Backup Data: Fixtures, dumpdata, loaddata, and inspectdb
Delete Data: Flush, sqlflush, and sqlsequencereset
Interact with Data: dbshell
Django Model Initial Data Setup
Hard-code predefined records in Python migration file
SQL script with SQL statements
Django fixture file
Django Model Signals
Built-In Django Model Signals
Listen for Django Model Signals
Emit Custom Signals in Django Model Signals
Django Models Outside of models.py
Django Models Inside Apps in the Models Folder
Django Models Inside Apps in Custom Folders
Django Models Outside Apps and Model Assignment to Other Apps
Django Models and Multiple Databases
Multiple Databases for Django Models: using
Multiple Databases for Django Tools: --database
Multiple Database Routers: DATABASE_ROUTERS setting
Chapter 8: Django Model Queries and Managers
CRUD Single Records in Django Models
Create a Single Record with save() or create()
Read a Single Record with get() or get_or_create()
Update a Single Record with save(), update(), update_or_create(), or refresh_from_db()
Delete a Single Record with delete()
CRUD Multiple Records in Django Models
Create Multiple Records with bulk_create()
Read Multiple Records with all(), filter(), exclude(), or in_bulk()
Understanding a QuerySet: Lazy Evaluation and Caching
Read Performance Methods: defer(), only(), values(), values_list(), iterator(), exists(), and none()
Update Multiple Records with update() or select_for_update()
Delete Multiple Records with delete()
CRUD Relationship Records Across Django Models
One to Many CRUD Operations
Many to Many CRUD Operations
One to One CRUD Operations
Read Performance Relationship Methods: select_related() and prefetch_related()
Model Queries by SQL Keyword
WHERE Queries: Django Field Lookups
=/EQUAL and !=/NOT EQUAL queries: exact, iexact
AND queries
OR queries: Q() objects
IS and IS NOT queries: isnull
IN queries: in
LIKE and ILIKE queries: contains, icontains, startswith, istartswith, endswith, iendswith
REGEXP queries: regex, iregex
>/GREATER THAN and
Date and time queries: Range, date, year, month, day, week, week_day, time, hour, minute, second
DISTINCT Queries
Dates and times queries: dates() and datetimes()
ORDER Queries: order_by() and reverse()
LIMIT Queries
LIMIT and OFFSET queries: Python slice syntax
Pseudo LIMIT 1 order queries: first() and last()
Pseudo LIMIT 1 date and time queries: latest() and earliest()
Merge Queries
QuerySet merger: Pipe and itertools.chain
UNION queries: union()
INTERSECT queries: intersection()
EXCEPT queries: difference()
Aggregation Queries
COUNT queries: count() method and Count() class
MAX, MIN, SUM, AVG, VARIANCE and STDDEV queries: Max(), Min(), Sum(), Avg(), Variance(), and StdDev() classes
Expression and Function Queries
SQL expression queries: F expressions
SQL function queries: Func expressions and Django database functions
SQL subqueries: Subquery expressions
Model Queries with Raw (Open-Ended) SQL
SQL Queries with a Model Manager’s raw() Method
SQL Queries with Python’s DB API
Model Managers
Custom and Multiple Model Managers
Custom Model Managers and QuerySet Classes with Methods
Custom Reverse Model Managers for Related Models
Chapter 9: Django Model Forms and Class Views
Django Model Form Structure and Workflow
Create Django Model Forms
Django Model Form Options and Field Mapping
Model Form Required Options: Model and Fields or Exclude
Model Form Default Field Mapping
Model Form New and Custom Fields: Widgets, Labels, help_texts, error_messages, field_classes, and localize_fields
Django Model Forms with Relationships
ModelChoiceField and ModelMultipleChoiceField Form Field Options: queryset, empty_label, to_field_name, and label_from_instance
Django Model Form Processing
Model Form Initialization: Initial and Instance
Model Form Validation
Django Model Formsets
Model Formset Factory
Class-Based Views with Models
Create Model Records with the Class-Based View CreateView
CreateView Fields and Methods
Basic CreateView options: Model, form_class, and success_url fields
Customize template name, MIME type and context: template_name and content_type fields and get_context_data( ) method
Customize form initialization and validation: Initial field, get_initial( ), get_form( ), form_valid( ), and form_invalid( ) methods
Customize view method workflow: get() and post() methods
Read Model Records with the Class-Based Views ListView and DetailView
ListView Fields and Methods
Basic ListView option: Model field
Customize template context reference name: context_object_name
Customize record list: Queryset and ordering fields and pagination behavior
DetailView Fields and Methods
Basic DetailView options: Model field and url with pk parameter
Customize url and query parameters: pk_url_kwarg, slug_field and slug_url_kwarg
Update Model Records with the Class-Based View UpateView
UpdateView Fields and Methods
Basic UpdateView options: Model, form_class and success_url fields, and url with pk parameter
Delete Records with the Class-Bases View DeleteView
DeleteView Fields and Methods
Basic DeleteView options: Model and success_url fields and url with pk parameter
Class-Based Views with Mixins
Chapter 10: Django User Management
Introduction to the Django User System
User Types, Subtypes, Groups, and Permissions
Create Users
Manage Users
Create and Manage Groups
Permission Types
User Permissions: Superuser, Staff, and Active
Model Permissions: Add, Change, Delete, and Custom
Model Meta permission options: default_permissions and permissions
Permission Checks and Enforcement
View Method Permission Checks
URL Permission Checks
Template Permission Checks
Class-Based View Permission Checks
User Authentication and Auto-Management
Login and Logout Workflow
Password Change Workflow
Password Reset Workflow
User Signup Workflow
Custom User Model Fields
Custom Authentication Back Ends
User Management with Django allauth
Install and Set Up django-allauth
First Log In and Log Out with Superuser in Django allauth
User Signup with Django allauth
Password Reset and Change with Django allauth
Add and Change User Email with Django allauth
Change Templates for Django allauth
Models and Database Tables Behind Django allauth
Social Authentication with Django allauth
Set Up Django allauth for Different Social Providers
Set Up Facebook with Django allauth
Set Up Google with Django allauth
Set Up Twitter with Django allauth
Chapter 11: Django admin Management
Set Up Django Models in the Django admin
Django admin Read Record Options
Record Display: list_display, format_html, empty_value_display
Record Order: admin_order_field and ordering
Record Links and Inline Edit: list_display_links and list_editable
Record Pagination: list_per_page, list_max_show_all, paginator
Record Search: search_fields, list_filter, show_full_result_count, preserve_filters
Record Dates: date_hierarchy
Record Actions: actions_on_top, actions_on_bottom, actions
Record Relationships
Display: list_display (continued)
Order: admin_order_field (continued)
Search: search_fields and list_filter (continued), admin.RelatedOnly FieldListFilter, list_select_related
Django admin Create, Update, Delete Record Options
Record Forms: fields, readonly_fields, exclude, fieldsets, formfield_overrides, form, prepopulated_fields
Actions, Links, and Positions: save_on_top, save_as(Clone records), save_as_continue and view_on_site
Relationships: filter_horizontal, filter_vertical, radio_fields, raw_id_fields, inlines
Django admin Custom Page Layout, Data, and Behaviors
Django admin Custom Global Values for Default Templates
Django admin Custom Page Layout with Custom Templates
Django admin Custom Static Resources
Django admin Custom Data and Behaviors with admin Class Fields and Methods
Django admin CRUD Permissions
Multiple Django admin Sites
Chapter 12: REST Services with Django
REST Services in Django
Standard View Method Designed as REST Service
Django REST Framework3
Django Tastypie Framework4
Django REST Framework Concepts and Introduction
Serializers and Views
Class-Based Views
Mixins and Generic Class-Based Views
View Sets and Routers
Django REST Framework Security
Set Up REST Framework Services Permissions
Set Up REST Framework Login Page
Appendix A: Python Basics
Strings, Unicode, and Other Annoying Text Behaviors
Methods Arguments: Default, optional, *args, and **kwargs
Classes and Subclasses
Loops, Iterators, and Generators
List Comprehensions, Generator Expressions, Maps, and Filters
Lambda Keyword for Anonymous Methods
Index