Mastering Django: Core
By Nigel George
()
About this ebook
Related to Mastering Django
Related ebooks
Learning jQuery Rating: 4 out of 5 stars4/5Flask By Example Rating: 0 out of 5 stars0 ratingsLearning PostgreSQL Rating: 1 out of 5 stars1/5MEAN Web Development Rating: 5 out of 5 stars5/5Node.js Design Patterns Rating: 4 out of 5 stars4/5Web Application Development with MEAN Rating: 0 out of 5 stars0 ratingsLearning Website Development with Django Rating: 0 out of 5 stars0 ratingsLearning Flask Framework Rating: 4 out of 5 stars4/5Django Project Blueprints Rating: 0 out of 5 stars0 ratingsDjango Design Patterns and Best Practices Rating: 5 out of 5 stars5/5React to Python: Creating React Front-End Web Applications with Python Rating: 0 out of 5 stars0 ratingsWeb Development with Django Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsDesigning Microservices using Django: Structuring, Deploying and Managing the Microservices Architecture with Django Rating: 0 out of 5 stars0 ratingsLaravel 5.x Cookbook Rating: 0 out of 5 stars0 ratingsMastering Python Rating: 0 out of 5 stars0 ratingsMastering Python Regular Expressions Rating: 5 out of 5 stars5/5Testing Python: Applying Unit Testing, TDD, BDD and Acceptance Testing Rating: 4 out of 5 stars4/5React Native By Example Rating: 0 out of 5 stars0 ratingsMastering Objectoriented Python Rating: 5 out of 5 stars5/5NumPy Beginner's Guide Rating: 5 out of 5 stars5/5Node.js in Practice Rating: 0 out of 5 stars0 ratingsAdvance Core Python Programming: Begin your Journey to Master the World of Python (English Edition) Rating: 4 out of 5 stars4/5PHP Reactive Programming Rating: 0 out of 5 stars0 ratingsFull Stack Developer A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsLaravel 5 Essentials Rating: 0 out of 5 stars0 ratingsPython 3 Object Oriented Programming Rating: 4 out of 5 stars4/5Laravel Application Development Cookbook Rating: 0 out of 5 stars0 ratingsThe Ruby Workshop: Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsC# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsSpies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5
Reviews for Mastering Django
0 ratings0 reviews
Book preview
Mastering Django - Nigel George
Table of Contents
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Why subscribe?
Preface
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Introduction to Django and Getting Started
Introducing Django
Django's history
Installing Django
Installing Python
Python versions
Installation
Installing a Python Virtual Environment
Installing Django
Setting up a database
Starting a project
Django settings
The development server
The Model-View-Controller (MVC) design pattern
What's next?
2. Views and URLconfs
Your first Django-powered page: Hello World
Your first view
Your first URLconf
Regular expressions
A quick note about 404 errors
A quick note about the site root
How Django processes a request
Your second view: dynamic content
URLconfs and loose coupling
Your third view: dynamic URLs
Django's pretty error pages
What's next?
3. Templates
Template system basics
Using the template system
Creating template objects
Rendering a template
Dictionaries and contexts
Multiple contexts, same template
Context variable lookup
Method call behavior
How invalid variables are handled
Basic template-tags and filters
Tags
if/else
for
ifequal/ifnotequal
Comments
Filters
Philosophies and limitations
Using templates in views
Template loading
Template directories
render()
Template subdirectories
The include template tag
Template inheritance
What's next?
4. Models
The dumb
way to do database queries in views
Configuring the database
Your first app
Defining Models in Python
Your first model
Installing the Model
Basic data access
Adding model string representations
Inserting and updating data
Selecting objects
Filtering data
Retrieving single objects
Ordering data
Chaining lookups
Slicing data
Updating multiple objects in one statement
Deleting objects
What's next?
5. The Django Admin Site
Using the admin site
Start the development server
Enter the admin site
Adding your models to the admin site
Making fields optional
Making date and numeric fields optional
Customizing field labels
Custom model admin classes
Customizing change lists
Customizing edit forms
Users, groups, and permissions
When and why to use the admin interface-and when not to
What's next?
6. Forms
Getting data from the Request Object
Information about the URL
Other information about the Request
Information about submitted data
A simple form-handling example
Query string parameters
Improving our simple form-handling example
Simple validation
Making a contact form
Your first form class
Tying form objects into views
Changing how fields are rendered
Setting a maximum length
Setting initial values
Custom validation rules
Specifying labels
Customizing form design
What's next?
7. Advanced Views and URLconfs
URLconf Tips and Tricks
Streamlining function imports
Special-Casing URLs in debug mode
Named groupsPreview
The matching/grouping algorithm
What the URLconf searches against
Captured arguments are always strings
Specifying defaults for view arguments
Performance
Error handling
Including other URLconfs
Captured parameters
Passing extra options to view functions
Passing extra options to include()
Reverse resolution of URLs
Examples
Naming URL patterns
URL namespaces
Reversing namespaced URLs
URL namespaces and included URLconfs
What's next?
8. Advanced Templates
Template language review
Requestcontext and context processors
auth
DEBUG
i18n
MEDIA
static
csrf
Request
messages
Guidelines for writing our own context processors
Automatic HTML escaping
How to turn it off
For individual variables
For template blocks
Automatic escaping of string literals in filter arguments
Inside Template loading
The DIRS option
Loader types
Filesystem loader
App directories loader
Other loaders
Extending the template system
Code layout
Creating a template library
Custom template tags and filters
Writing custom template filters
Registering custom filters
Template filters that expect strings
Filters and auto-escaping
Filters and time zones
Writing custom template tags
Simple tags
Inclusion tags
Assignment tags
Advanced custom template tags
A quick overview
Writing the compilation function
Writing the renderer
Auto-escaping Considerations
Thread-safety Considerations
Registering the tag
Passing template variables to The Tag
Setting a variable in the context
Variable scope in context
Parsing until another block tag
Parsing until another block tag, and saving contents
What's next
9. Advanced Models
Related objects
Accessing ForeignKey values
Accessing many-to-many values
Managers
Adding extra manager methods
Modifying initial manager QuerySets
Model methods
Overriding predefined model methods
Executing raw SQL queries
Performing raw queries
Model table names
Mapping query fields to model fields
Index lookups
Deferring model fields
Adding annotations
Passing parameters into raw()
Executing custom SQL directly
Connections and cursors
Adding extra Manager methods
What's next?
10. Generic Views
Generic views of objects
Making friendly
template contexts
Adding extra context
Viewing subsets of objects
Dynamic filtering
Performing extra work
What's next?
11. User Authentication in Django
Overview
Using the Django authentication system
User objects
Creating superusers
Creating users
Changing passwords
Permissions and authorization
Default permissions
Groups
Programmatically creating permissions
Permission caching
Authentication in web requests
How to log a user in
How to log a user out
Limiting access to logged-in users
The raw way
The login_required decorator
Limiting access to logged-in users that pass a test
The permission_required() decorator
Session invalidation on password change
Authentication views
Login
Logout
Logout_then_login
Password_change
Password_change_done
Password_reset
Password_reset_done
Password_reset_confirm
Password_reset_complete
The redirect_to_login helper function
Built-in forms
Authenticating data in templates
Users
Permissions
Managing users in the admin
Creating users
Changing passwords
Password management in Django
How Django stores passwords
Using Bcrypt with Django
Password truncation with BCryptPasswordHasher
Other Bcrypt implementations
Increasing the work factor
Password upgrading
Manually managing a user's password
Customizing authentication in Django
Other authentication sources
Specifying authentication backends
Writing an authentication backend
Handling authorization in custom backends
Authorization for anonymous users
Authorization for inactive users
Handling object permissions
Custom permissions
Extending the existing user model
Substituting a custom user model
What's next?
12. Testing in Django
Introduction to testing
Introducing automated testing
What are automated tests?
So why create tests?
Basic testing strategies
Writing a test
Creating a test
Running tests
Testing tools
The test client
Provided TestCase classes
Simple TestCase
Transaction TestCase
TestCase
LiveServerTestCase
Test cases features
Default test client
Fixture loading
Overriding settings
settings()
modify_settings()
override_settings()
modify_settings()
Assertions
Email services
Management commands
Skipping tests
The test database
Using different testing frameworks
What's next?
13. Deploying Django
Preparing your codebase for production
Deployment checklist
Critical settings
SECRET_KEY
DEBUG
Environment-specific settings
ALLOWED_HOSTS
CACHES
DATABASES
EMAIL_BACKEND and Related Settings
STATIC_ROOT and STATIC_URL
MEDIA_ROOT and MEDIA_URL
HTTPS
CSRF_COOKIE_SECURE
SESSION_COOKIE_SECURE
Performance optimizations
CONN_MAX_AGE
TEMPLATES
Error reporting
LOGGING
ADMINS and MANAGERS
Customize the default error views
Using a virtualenv
Using different settings for production
Deploying Django to a production server
Deploying Django with Apache and mod_wsgi
Basic configuration
Using mod_wsgi daemon Mode
Serving files
Serving the admin files
If you get a UnicodEncodError
Serving static files in production
Serving the site and your static files from the same server
Serving static files from a dedicated server
Serving static files from a cloud service or CDN
Scaling
Running on a single server
Separating out the database server
Running a separate media server
Implementing load balancing and redundancy
Going big
Performance tuning
There's no such thing as Too Much RAM
Turn off Keep-Alive
Use Memcached
Use Memcached often
Join the conversation
What's next?
14. Generating Non-HTML Content
The basics: views and MIME types
Producing CSV
Streaming large CSV files
Using the template system
Other text-based formats
Generating PDF
Install ReportLab
Write your view
Complex PDF's
Further resources
Other possibilities
The syndication feed framework
The high-level framework
Overview
Feed classes
A simple example
A complex example
Specifying the type of feed
Enclosures
Language
URLs
Publishing Atom and RSS Feeds in tandem
The low-level framework
SyndicationFeed classes
SyndicationFeed.__init__()
SyndicationFeed.add_item()
SyndicationFeed.write()
SyndicationFeed.writeString()
Custom feed generators
SyndicationFeed.root_attributes(self, )
SyndicationFeed.add_root_elements(self, handler)
SyndicationFeed.item_attributes(self, item)
SyndicationFeed.add_item_elements(self, handler, item)
The Sitemap framework
Installation
Initialization
Sitemap classes
A simple example
Sitemap class reference
items
location
lastmod
changefreq
priority
protocol
i18n
Shortcuts
Example
Sitemap for static views
Creating a sitemap index
Template customization
Context variables
Index
Sitemap
Pinging google
django.contrib.syndication.ping_google()
Pinging Google via manage.py
What's next?
15. Django Sessions
Enabling sessions
Configuring the session engine
Using database-backed sessions
Using cached sessions
Using file-based sessions
Using cookie-based sessions
Using Sessions in Views
flush()
set_test_cookie()
test_cookie_worked()
delete_test_cookie()
set_expiry(value)
get_expiry_age()
get_expiry_date()
get_expire_at_browser_close()
clear_expired()
cycle_key()
Session object guidelines
Session serialization
Bundled serializers
serializers.JSONSerializer
serializers.PickleSerializer
Write your own serializer
Setting test cookies
Using sessions out of views
When sessions are saved
Browser-length sessions vs. persistent sessions
Clearing the session store
What's next
16. Djangos Cache Framework
Setting up the cache
Memcached
Database caching
Creating the cache table
Multiple databases
Filesystem caching
Local-memory caching
Dummy caching (for development)
Using a custom cache backend
Cache arguments
The per-site cache
The per-view cache
Specifying per-view Cache in the URLconf
Template fragment caching
The low-level cache API
Accessing the cache
Basic usage
Cache key prefixing
Cache versioning
Cache key transformation
Cache key warnings
Downstream caches
Using vary headers
Controlling cache: using other headers
What's next?
17. Django Middleware
Activating middleware
Hooks and application order
Writing your own middleware
process_request
process_view
process_template_response
process_response
Dealing with streaming responses
process_exception
__init__
Marking middleware as unused
Additional guidelines
Available middleware
Cache middleware
Common middleware
GZip middleware
Conditional GET middleware
Locale middleware
Message middleware
Security middleware
HTTP strict transport security
X-content-type-options: nosniff
X-XSS-protection
SSL redirect
Session middleware
Site middleware
Authentication middleware
CSRF protection middleware
X-Frame-options middleware
Middleware ordering
What's next?
18. Internationalization
Definitions
Internationalization
Localization
locale name
language code
message file
translation string
format file
Translation
Internationalization: in Python code
Standard translation
Comments for Translators
Marking strings as No-Op
Pluralization
Contextual markers
Lazy translation
Model fields and relationships
Model verbose names values
Model methods short_description attribute values
Working with lazy translation objects
Lazy translations and plural
Joining strings: string_concat()
Other uses of lazy in delayed translations
Localized names of languages
Internationalization: In template code
trans template tag
blocktrans template tag
String literals passed to tags and filters
Comments for translators in templates
Switching language in templates
Other tags
Internationalization: In Javascript code
The javascript_catalog view
Using the JavaScript translation catalog
Note on performance
Internationalization: In URL patterns
Language prefix in URL patterns
Translating URL patterns
Reversing in templates
Localization: How to create language files
Message files
Compiling message files
Creating message files from JavaScript source code
gettext on windows
Customizing the makemessages command
Explicitly setting the active language
Using translations outside views and templates
Implementation notes
Specialties of Django translation
How Django discovers language preference
How Django discovers translations
What's next?
19. Security in Django
Django's built in security features
Cross Site Scripting (XSS) protection
Cross Site Request Forgery (CSRF) protection
How to use it
AJAX
Other template engines
The decorator method
Rejected requests
How it works
Caching
Testing
Limitations
Edge cases
Utilities
django.views.decorators.csrf.csrf_exempt(view)
django.views.decorators.csrf.requires_csrf_token(view)
django.views.decorators.csrf.ensure_csrf_cookie(view)
Contrib and reusable apps
CSRF settings
SOL injection protection
Clickjacking protection
An example of clickjacking
Preventing clickjacking
How to use it
Setting X-Frame-Options for all responses
Setting X-Frame-Options per view
Limitations
Browsers that support X-Frame-Options
SSL/HTTPS
HTTP strict transport security
Host header validation
Session security
User-Uploaded content
Additional security tips
Archive of security issues
Cryptographic signing
Protecting the SECRET_KEY
Using the low-level API
Using the salt argument
Verifying timestamped values
Protecting complex data structures
Security middleware
What's next?
20. More on Installing Django
Running other databases
Installing Django manually
Upgrading Django
Remove any old versions of Django
Installing a Distribution-specific package
Installing the development version
What's next?
21. Advanced Database Management
General notes
Persistent connections
Connection management
Caveats
Encoding
postgreSQL notes
Optimizing postgreSQL's configuration
Isolation level
Indexes for varchar and text columns
MySQL notes
Version support
Storage engines
MySQL DB API drivers
mySQLdb
mySQLclient
mySQL connector/python
Timezone definitions
Creating your database
Collation settings
Connecting to the database
Creating your tables
Table names
Savepoints
Notes on specific fields
Character fields
Fractional seconds support for time and datetime fields
TIMESTAMP columns
Row locking with Queryset.Select_For_Update()
Automatic typecasting can cause unexpected results
SQLite notes
Substring matching and case sensitivity
Old SQLite and CASE expressions
Using newer versions of the SQLite DB-API 2.0 driver
Database is locked errors
queryset.Select_For_Update() not Supported
pyformat parameter style in raw queries not supported
Parameters not quoted in connection.queries
Oracle notes
Connecting to the database
Threaded option
INSERT ... RETURNING INTO
Naming issues
NULL and empty strings
Textfield limitations
Using a 3rd-Party database backend
Integrating Django with a legacy database
Give Django your database parameters
Auto-generate the models
Install the core Django tables
Cleaning up generated models
Test and tweak
What's next?
A. Model Definition Reference
Fields
Field name restrictions
FileField notes
FileField FileField.upload_to
FileField.storage
FileField and FieldFile
FieldFile.url
FieldFile.open(mode='rb')
FieldFile.close()
FieldFile.save(name, content, save=True)
FieldFile.delete(save=True)
Universal field options
Field attribute reference
Attributes for fields
Field.auto_created
Field.concrete
Field.hidden
Field.is_relation
Field.model
Attributes for fields with relations
Field.many_to_many
Field.many_to_one
Field.one_to_many
Field.one_to_one
Field.related_model
Relationships
ForeignKey
Database representation
Arguments
limit_choices_to
related_name
related_query_name
to_field
db_constraint
on_delete
swappable
ManyToManyField
Database representation
Arguments
related_name
related_query_name
limit_choices_to
symmetrical
through
through_fields
db_table
db_constraint
swappable
OneToOneField
parent_link
Model metadata options
B. Database API Reference
Creating objects
Saving changes to objects
Saving ForeignKey and ManyToManyField fields
Retrieving objects
Retrieving all objects
Retrieving specific objects with filters
Chaining filters
Filtered querysets are unique
QuerySets are lazy
Retrieving a single object with get
Other queryset methods
Limiting querysets
Field lookups
Lookups that span relationships
Spanning multi-valued relationships
Filters can reference fields on the model
The pk lookup shortcut
Escaping percent signs and underscores in LIKE statements
Caching and querysets
When querysets are not cached
Complex lookups with Q objects
Comparing objects
Deleting objects
Copying model instances
Updating multiple objects at once
Related objects
One-to-many relationships
Forward
Following relationships backward
Using a custom reverse manager
Additional methods to handle related objects
Many-to-many relationships
One-to-one relationships
Queries over related objects
Falling back to raw SQL
C. Generic View Reference
Common arguments to generic views
Simple generic views
Rendering a template-TemplateView
Redirecting to another URL
Attributes
url
pattern_name
permanent
query_string
Methods
List/detail generic views
Lists of objects
Detail views
Date-Based Generic Views
ArchiveIndexView
YearArchiveView
MonthArchiveView
WeekArchiveView
DayArchiveView
TodayArchiveView
DateDetailView
Form handling with class-based views
Basic forms
Model forms
Models and request.user
AJAX example
D. Settings
What's a settings file?
Default settings
Seeing which settings you've changed
Using settings in Python code
Altering settings at runtime
Security
Creating your own settings
DJANGO_SETTINGS_MODULE
The django-admin utility
On the server (mod_wsgi)
Using settings without setting DJANGO_SETTINGS_MODULE
Custom default settings
Either configure() or DJANGO_SETTINGS_MODULE is required
Available settings
Core settings
Auth
Messages
Sessions
Sites
Static files
E. Built-in Template Tags and Filters
Built-in tags
autoescape
block
comment
csrf_token
cycle
debug
extends
filter
firstof
for
for... empty
if
Boolean operators
Complex expressions
Filters
ifchanged
ifequal
ifnotequal
include
load
lorem
now
regroup
spaceless
templatetag
url
verbatim
widthratio
with
Built-in filters
add
addslashes
capfirst
center
cut
date
default
default_if_none
dictsort
dictsortreversed
divisibleby
escape
escapejs
filesizeformat
first
floatformat
get_digit
iriencode
join
last
length
length_is
linebreaks
linebreaksbr
linenumbers
ljust
lower
make_list
phone2numeric
pluralize
pprint
random
rjust
safe
safeseq
slice
slugify
stringformat
striptags
time
timesince
timeuntil
title
truncatechars
truncatechars_html
truncatewords
truncatewords_html
unordered_list
upper
urlencode
urlize
urlizetrunc
wordcount
wordwrap
yesno
Internationalization tags and filters
i18n
l10n
tz
Other tags and filters libraries
static
get_static_prefix
get_media_prefix
F. Request and Response Objects
HttpRequest objects
Attributes
Methods
QueryDict objects
Methods
HttpResponse objects
Usage
Attributes
Methods
HttpResponse subclasses
JsonResponse Objects
Usage
StreamingHttpResponse objects
Performance considerations
Attributes
FileResponse objects
Error views
The 404 (page not found) view
The 500 (server error) view
The 403 (HTTP Forbidden) view
The 400 (bad request) view
Customizing error views
G. Developing Django with Visual Studio
Installing Visual Studio
Install PTVS and Web Essentials
Creating A Django project
Start a Django project
Django development in Visual Studio
Integration of Django management commands
Easy installation of Python packages
Easy installation of new Django apps
Mastering Django: Core
Mastering Django: Core
Copyright © 2016 Nigel George
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2016
Production reference: 1291116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78728-114-1
www.packtpub.com
Credits
About the Author
Nigel George is a business systems developer who specializes in the application of open source technologies to solve common business problems. He has a broad range of experience in software development—from writing database apps for small business to developing the back end and UI for a distributed sensor network at the University of Newcastle, Australia.
Nigel also has over 15 years experience in technical writing for business. He has written several training manuals and hundreds of technical procedures for corporations and Australian government departments. He has been using Django since version 0.96 and has written applications in C, C#, C++, VB, VBA, HTML, JavaScript, Python and PHP.
He has another book on Django—Beginning Django CMS—published by Apress in December 2015.
Nigel lives in Newcastle, NSW, Australia.
First and foremost, I would like to thank the original authors of the Django Book-Adrian Holovaty and Jacob Kaplan-Moss. They provided such a strong foundation that it has really been a delight writing this new edition.
Equal first in the shout out has to be the Django community. Vibrant and collaborative, the Django community is what really stood out to this cynical old businessman many years ago when I first discovered the new kid on the webframework block
. It’s your support that makes Django so great. Thank you.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
What you need for this book
Required programming knowledge
Readers of this book should understand the basics of procedural and object-oriented programming: control structures (such as if, while, or for), data structures (lists, hashes/dictionaries), variables, classes, and objects. Experience in web development is, as you may expect, very helpful, but it is not required to understand this book. Throughout the book, I try to promote best practices in web development for readers who lack this experience.
Required Python knowledge
At its core, Django is simply a collection of libraries written in the Python programming language. To develop a site using Django, you write Python code that uses these libraries. Learning Django, then, is a matter of learning how to program in Python and understanding how the Django libraries work. If you have experience programming in Python, you should have no trouble diving in. By and large, the Django code doesn't perform a lot of magic (that is, programming trickery whose implementation is difficult to explain or understand). For you, learning Django will be a matter of learning Django's conventions and APIs.
If you don't have experience programming in Python, you're in for a treat. It's easy to learn and a joy to use! Although this book doesn't include a full Python tutorial, it highlights Python features and functionality where appropriate, particularly when code doesn't immediately make sense. Still, I recommend you read the official Python tutorial (for more information visit http://docs.python.org/tut/). I also recommend Mark Pilgrim's free book Dive Into Python, available online at http://www.diveintopython.net/ and published in print by Apress.
Required Django version
This book covers Django 1.8 LTS. This is the long term support version of Django, with full support until at least April 2018.
If you have an early version of Django, it is recommended that you upgrade to the latest version of Django 1.8 LTS. At the time of printing (July 2016), the most current production version of Django 1.8 LTS is 1.8.13.
If you have installed a later version of Django, please note that while Django's developers maintain backwards compatibility as much as possible, some backwards incompatible changes do get introduced occasionally. The changes in each release are always covered in the release notes, which you can find at https://docs.djangoproject.com/en/dev/releases/.
For any queries visit: http://masteringdjango.com.
Who this book is for
This book assumes you have a basic understanding of the Internet and programming. Experience with Python or Django would be an advantage, but is not necessary. It is ideal for beginner to intermediate programmers looking for a fast, secure, scalable, and maintainable alternative web development platform to those based on PHP, Java, and dotNET.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Type python at a command prompt (or in Applications/Utilities/Terminal, in OS X).
A block of code is set as follows:
from django.http import HttpResponse
def hello(request):
return HttpResponse(Hello world
)
Any command-line input or output is written as follows:
Python 2.7.5 (default, June 27 2015, 13:20:20)
[GCC x.x.x] on xxx
Type help
, copyright
, credits
or license
for more information.
>>>
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: You should see the text Hello world-the output of your Django view (Figure 2-1).
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in 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 at 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.
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 could 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 to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted 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 [email protected] 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
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Chapter 1. Introduction to Django and Getting Started
Introducing Django
Great open source software almost always comes about because one or more clever developers had a problem to solve and no viable or cost effective solution available. Django is no exception. Adrian and Jacob have long since retired from the project, but the fundamentals of what drove them to create Django live on. It is this solid base of real-world experience that has made Django as successful as it is. In recognition of their contribution, I think it best we let them introduce Django in their own words (edited and reformatted from the original book).
By Adrian Holovaty and Jacob Kaplan-Moss-December 2009
In the early days, web developers wrote every page by hand. Updating a website meant editing HTML; a redesign involved redoing every single page, one at a time. As websites grew and became more ambitious, it quickly became obvious that that approach was tedious, time-consuming, and ultimately untenable.
A group of enterprising hackers at National Center for Supercomputing Applications (the NCSA where Mosaic, the first graphical web browser, was developed) solved this problem by letting the web server spawn external programs that could dynamically generate HTML. They called this protocol the Common Gateway Interface (CGI), and it changed the web forever. It's hard now to imagine what a revelation CGI must have been: instead of treating HTML pages as simple files on disk, CGI allows you to think of your pages as resources generated dynamically on demand.
The development of CGI ushered in the first generation of dynamic websites. However, CGI has its problems: CGI scripts need to contain a lot of repetitive boilerplate code, they make code reuse difficult, and they can be difficult for first-time developers to write and understand.
PHP fixed many of these problems, and it took the world by storm—it is now the most popular tool used to create dynamic websites, and dozens of similar languages (ASP, JSP, and so on.) followed PHP's design closely. PHP's major innovation is its ease of use: PHP code is simply embedded into plain HTML; the learning curve for someone who already knows HTML is extremely shallow.
But PHP has its own problems; it is very ease of use encourages sloppy, repetitive, ill-conceived code. Worse, PHP does little to protect programmers from security vulnerabilities, and thus many PHP developers found themselves learning about security only once it was too late.
These and similar frustrations led directly to the development of the current crop of third-generation web development frameworks. With this new explosion of web development comes yet another increase in ambition; web developers are expected to do more and more every day.
Django was invented to meet these new ambitions.
Django's history
Django grew organically from real-world applications written by a web development team in Lawrence, Kansas, USA. It was born in the fall of 2003, when the web programmers at the Lawrence Journal-World newspaper, Adrian Holovaty, and Simon Willison, began using Python to build applications.
The World Online team, responsible for the production and maintenance of several local news sites, thrived in a development environment dictated by journalism deadlines. For the sites—including LJWorld.com, Lawrence.com, and KUsports.com—journalists (and management) demanded that features be added and entire applications be built on an intensely fast schedule, often with only day's or hour's notice. Thus, Simon and Adrian developed a time-saving web development framework out of necessity—it was the only way they could build maintainable applications under the extreme deadlines.
In summer 2005, after having developed this framework to a point where it was efficiently powering most of World Online's sites, the team, which now included Jacob Kaplan-Moss, decided to release the framework as open source software. They released it in July 2005 and named it Django, after the jazz guitarist Django Reinhardt.
This history is relevant because it helps explain two key things. The first is Django's sweet spot.
Because Django was born in a news environment, it offers several features (such as its admin site, covered in Chapter 5, The Django Admin Site) that are particularly well suited for content
sites such as Amazon.com, craigslist.org, and washingtonpost.com that offer dynamic and database-driven information.
Don't let that turn you off, though Django is particularly good for developing those sorts of sites, that doesn't preclude it from being an effective tool for building any sort of dynamic website. (There's a difference between being particularly effective at something and being ineffective at other things.)
The second matter to note is how Django's origins have shaped the culture of its open source community. Because Django was extracted from real-world code, rather than being an academic exercise or commercial product, it is acutely focused on solving web development problems that Django's developers themselves have faced—and continue to face. As a result, Django itself is actively improved on an almost daily basis. The framework's maintainers have a vested interest in making sure Django saves developers time, produces applications that are easy to maintain and performs well under load.
Django lets you build deep, dynamic, interesting sites in an extremely short time. Django is designed to let you focus on the fun, interesting parts of your job while easing the pain of the repetitive bits. In doing so, it provides high-level abstractions of common web development patterns, shortcuts for frequent programming tasks, and clear conventions on how to solve problems. At the same time, Django tries to stay out of your way, letting you work outside the scope of the framework as needed.
We wrote this book because we firmly believe that Django makes web development better. It's designed to quickly get you moving on your own Django projects, and then ultimately teach you everything you need to know to successfully design, develop, and deploy a site that you'll be proud of.
Getting Started
There are two very important things you need to do to get started with Django:
Install Django (obviously); and
Get a good understanding of the Model-View-Controller (MVC) design pattern.
The first, installing Django, is really simple and detailed in the first part of this chapter. The second is just as important, especially if you are a new programmer or coming from using a programming language that does not clearly separate the data and logic behind your website from the way it is displayed. Django's philosophy is based on loose coupling, which is the underlying philosophy of MVC. We will be discussing loose coupling and MVC in much more detail as we go along, but if you don't know much about MVC, then you best not skip the second half of this chapter because understanding MVC will make understanding Django so much easier.
Installing Django
Before you can start learning how to use Django, you must first install some software on your computer. Fortunately, this is a simple three step process:
Install Python.
Install a Python Virtual Environment.
Install Django.
If this does not sound familiar to you don't worry, in this chapter, lets assume that you have never installed software from the command line before and will lead you through it step by step.
I have written this section for those of you running Windows. While there is a strong *nix and OSX user base for Django, most new users are on Windows. If you are using Mac or Linux, there are a large number of resources on the Internet; with the best place to start being Django's own installation instructions. For more information visit https://docs.djangoproject.com/en/1.8/topics/install/.
For Windows users, your computer can be running any recent version of Windows (Vista, 7, 8.1, or 10). This chapter also assumes you're installing Django on a desktop or laptop computer and will be using the development server and SQLite to run all the example code in this book. This is by far the easiest and the best way to setup Django when you are first starting out.
If you do want to go to a more advanced installation of Django, your options are covered in Chapter 13 , Deploying Django, Chapter 20, More on Installing Django, and Chapter 21 , Advanced Database Management.
Note
If you are using Windows, I recommend that you try out Visual Studio for all your Django development. Microsoft has made a significant investment in providing support for Python and Django programmers. This includes full IntelliSense support for Python/Django and incorporation of all of Django's command line tools into the VS IDE.
Best of all it's entirely free. I know, who would have expected that from M$??, but it's true!
See Appendix G, Developing Django with Visual Studio for a complete installation guide for Visual Studio Community 2015, as well as a few tips on developing Django in Windows.
Installing Python
Django itself is written purely in Python, so the first step in installing the framework is to make sure you have Python installed.
Python versions
Django version 1.8 LTS works with Python version 2.7, 3.3, 3.4 and 3.5. For each version of Python, only the latest micro release (A.B.C) is supported.
If you are just trialling Django, it doesn't really matter whether you use Python 2 or Python 3. If, however, you are planning on eventually deploying code to a live website, Python 3 should be your first choice. The Python wiki (for more information visit https://wiki.python.org/moin/Python2orPython3, puts the reason behind this very succinctly:
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language
Unless you have a very good reason to use Python 2 (for example, legacy libraries), Python 3 is the way to go.
Tip
NOTE: All of the code samples in this book are written in Python 3
Installation
If you're on Linux or Mac OS X, you probably have Python already installed. Type python at a command prompt (or in Applications/Utilities/Terminal, in OS X). If you see something like this, then Python is installed:
Python 2.7.5 (default, June 27 2015, 13:20:20) [GCC x.x.x] on xxx
Type help
, copyright
, credits
or license
for more
information.
Note
You can see that, in the preceding example, Python interactive mode is running Python 2.7. This is a trap for inexperienced users. On Linux and Mac OS X machines, it is common for both Python 2 and Python 3 to be installed. If your system is like this, you need to type python3 in front of all your commands, rather than python to run Django with Python 3.
Assuming Python is not installed on your system, we first need to get the installer. Go to https://www.python.org/downloads/, and click the big yellow button that says Download Python 3.x.x.
At the time of writing, the latest version of Python is 3.5.1, but it may have been updated by the time you read this, so the numbers may be slightly different.
DO NOT download version 2.7.x as this is the old version of Python. All of the code in this book is written in Python 3, so you will get compilation errors if you try to run the code on Python 2.
Once you have downloaded the Python installer, go to your Downloads folder and double-click the file python-3.x.x.msi to run the installer. The installation process is the same as any other Windows program, so if you have installed software before, there should be no problem here, however, the is one extremely important customization you must make.
Note
Do not forget this next step as it will solve most problems that arise from an incorrect mapping of pythonpath (an important variable for Python installations) in Windows.
By default, the Python executable is not added to the Windows PATH statement. For Django to work properly, Python must be listed in the PATH statement. Fortunately, this is easy to rectify:
In Python 3.4.x, When the installer opens the customization window, the option Add python.exe to Path is not selected, you must change this to Will be installed on a local hard drive as shown in Figure 1.1.
Figure 1.1: Add Python to PATH (Version 3.4.x).
In Python 3.5.x you make sure Add Python 3.5 to PATH is checked before installing (Figure 1.2).
Figure 1.2: Add Python to PATH (Version 3.5.x).
Once Python is installed, you should be able to re-open the command window and type python at the command prompt and get something like this:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type help
, copyright
, credits
or license
for more
information.
>>>
While you are at it, there is one more important thing to do. Exit out of Python with CTRL+C. At the command prompt type, the following and hit enter:
python-m pip install-U pip
The output will be something similar to this:
C:\Users\nigel>python -m pip install -U pip Collecting pip Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB) 100% |################################| 1.2MB 198kB/s Installing collected packages: pip Found existing installation: pip 7.1.2 Uninstalling pip-7.1.2: Successfully uninstalled pip-7.1.2 Successfully installed pip-8.1.2
You don't need to understand exactly what this command does right now; put briefly pip is the Python package manager. It's used to install Python packages: pip is actually a recursive acronym for Pip Installs Packages. Pip is important for the next stage of our install process, but first, we need to make sure we are running the latest version of pip (8.1.2 at the time of writing), which is exactly what this command does.
Installing a Python Virtual Environment
Note
If you are going to use Microsoft Visual Studio (VS), you can stop here and jump to Appendix G, Developing Django with Visual Studio. VS only requires that you install Python, everything else VS does for you from inside the Integrated Development Environment (IDE).
All of the software on your computer operates interdependently—each program has other bits of software that it depends on (called dependencies) and settings that it needs to find the files and other software it needs to run (called environment variables).
When you are writing new software programs, it is possible (and common!) to modify dependencies and environment variables that your other software depends on. This can cause numerous problems, so should be avoided.
A Python virtual environment solves this problem by wrapping all the dependencies and environment variables that your new software needs into a file system separate from the rest of the software on your computer.
Note
Some of you who have looked at other tutorials will note that this step is often described as optional. This is not a view I support, nor is it supported by a number of Django's core developers.
Note
The advantages of developing Python applications (of which Django is one) within a virtual environment are manifest and not worth going through here. As a beginner, you just need to take my word for it—running a virtual environment for Django development is not optional.
The virtual environment tool in Python is called virtualenv and we install it from the command line using pip:
pip install virtualenv
The output from your command window should look something like this:
C:\Users\nigel>pip install virtualenv Collecting virtualenv Downloading virtualenv-15.0.2-py2.py3-none-any.whl (1.8MB) 100% |################################| 1.8MB 323kB/s Installing collected packages: virtualenv Successfully installed virtualenv-15.0.2
Once virtualenv is installed, you need to create a virtual environment for your project by typing:
virtualenv env_mysite
Note
Most examples on the Internet use env as your environment name. This is bad; principally because it's common to have several virtual environments installed to test different configurations, and env is not very descriptive. For example, you may be developing an application that must run on Python 2.7 and Python 3.4. Environments named env_someapp_python27 and env_someapp_python34 are going to be a lot easier to distinguish than if you had named them env and env1.
In this example, I have kept it simple as we will only be using one virtual environment for our project, so I have used env_mysite. The output from your command should look something like this:
C:\Users\nigel>virtualenv env_mysite Using base prefix 'c:\\users\\nigel\\appdata\\local\\programs\\python\\python35-32'
New python executable in
C:\Users\nigel\env_mysite\Scripts\python.exe
Installing setuptools, pip, wheel...done.
Once virtualenv has finished setting up your new virtual environment, open Windows Explorer and have a look at what virtualenv created for you. In your home directory, you will now see a folder called \env_mysite (or whatever name you gave the virtual environment). If you open the folder, you will see the following:
\Include
\Lib
\Scripts
\src
virtualenv has created a complete Python installation for you, separate from your other software, so you can work on your project without affecting any of the other software on your system.
To use this new Python virtual environment, we have to activate it, so let's go back to the command prompt and type the following:
env_mysite\scripts\activate
This will run the activate script inside your virtual environment's \scripts folder. You will notice your command prompt has now changed:
(env_mysite) C:\Users\nigel>
The (env_mysite) at the beginning of the command prompt lets you know that you are running in the virtual environment. Our next step is to install Django.
Installing Django
Now that we have Python and are running a virtual environment, installing Django is super easy, just type the command:
pip install django==1.8.13
This will instruct pip to install Django into your virtual environment. Your command output should look like this:
(env_mysite) C:\Users\nigel>pip install django==1.8.13 Collecting django==1.8.13 Downloading Django-1.8.13-py2.py3-none-any.whl (6.2MB) 100% |################################| 6.2MB 107kB/s Installing collected packages: django Successfully installed django-1.8.13
In this case, we are explicitly telling pip to install Django 1.8.13, which is the latest version of Django 1.8 LTS at the time of writing. If you are installing Django, it's good practice to check the Django Project website for the latest version of Django 1.8 LTS.
Note
In case you were wondering, typing in pip install django will install the latest stable release of Django. If you want information on installing the latest development release of Django, see Chapter 20, More On Installing Django.
For some post-installation positive feedback, take a moment to test whether the installation worked. At your virtual environment command prompt, start the Python interactive interpreter by typing python and hitting enter. If the installation was successful, you should be able to import the module django:
(env_mysite) C:\Users\nigel>python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type help
, copyright
, credits
or license
for more
information.
>>> import django >>> django.get_version() 1.8.13'
Setting up a database
This step is not necessary in order to complete any of the examples in this book. Django comes with SQLite installed by default. SQLite requires no configuration on your part. If you would like to work with a large database engines like PostgreSQL, MySQL, or Oracle, see Chapter 21, Advanced Database Management.
Starting a project
Once you've installed Python, Django and (optionally) your database server/library, you can take the first step in developing a Django application by creating a project.
A project is a collection of settings for an instance of Django. If this is your first time using Django, you'll have to take care of some initial setup. Namely, you'll need to auto-generate some code that establishes a Django project: a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings.
I am assuming at this stage you are still running the virtual environment from the previous installation step. If not, you will have to start it again with:
env_mysite\scripts\activate\
From your virtual environment command line, run the following command:
django-admin startproject mysite
This will create a mysite directory in your current directory (in this case \env_mysite\). If you want to create your project in a directory other than the root, you can create a new directory, change into that directory and run the startproject command from there.
Note
Warning!
You'll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names such as django
(which will conflict with Django itself) or test
(which conflicts with a built-in Python package).
Let's look at what startproject created:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py