You are on page 1of 19

Django: Web Development

with Python

From an idea to a prototype a complete guide


to web development with the Django framework

A course in three modules

BIRMINGHAM - MUMBAI
Django:Web Development with Python

Copyright 2016 Packt Publishing

All rights reserved. No part of this course 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 course to ensure the accuracy
of the information presented. However, the information contained in this course
is sold without warranty, either express or implied. Neither the authors, 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 course.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this course by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

Published on: August 2016

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78712-138-6
www.packtpub.com
Credits

Authors Content Development Editor


Samuel Dauzon Priyanka Mehta
Aidas Bendoraitis
Arun Ravindran Graphics
'LVKD+DULD

Reviewers
Jorge Armin Garcia Lopez Production Coordinator
Aparna Bhagat
Caleb Smith
Deepak Thukral
Patrick Chan
Jake Kronika
Jorge Armin Garcia Lopez
Shoubhik Bose
Kracekumar Ramaraju
Jai Vikram Singh Verma
Preface
Data science is hot right now, and the need for multi-talented developers is greater
than ever before. With a growing skills gap, the need for talented developers is
greater than ever before. A basic grounding in building apps with a framework as
minimalistic, powerful, and easy-to-learn as Django will be a useful skill to launch
you on a career as an entrepreneur or web developer.

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.

For some years, web development has evolved through frameworks. Web
GHYHORSPHQWKDVEHFRPHPRUHHIFLHQWDQGKDVLPSURYHGLQTXDOLW\'MDQJR
is a very sophisticated and popular framework. Django is based on the Python
programming language, where the code is clear and easy to read. Also, Django has
a lot of third-party modules that can be used in conjunction with your own apps.
'MDQJRKDVDQHVWDEOLVKHGDQGYLEUDQWFRPPXQLW\ZKHUH\RXFDQQGVRXUFHFRGH
get help, and contribute.

This course is a learning path that uses module-by-module pedagogy to help novice
developers learn how to easily deal with the Django framework. This course will also
provide you a basic grounding in the fundamental concepts of web development
with Python, as well as the hands-on experience in order to successfully build web
applications with Django.

[i]
Preface

What this learning path covers


Module 1, Django EssentialsDSUDFWLFDOJXLGHOOHGZLWKPDQ\UHDOZRUOGH[DPSOHVWR
build highly effective Django web application. It begins with step-by-step installation
of Python, PIP, and Django on Windows, Linux, and Mac OS..

Module 2, Web Development with Django Cookbook, covers varying complexities to help
you create multilingual, responsive, and scalable websites with Django.

Module 3, Django Design Patterns and Best Practices, This module will teach you common
design patterns to develop better Django code. Creating a successful web application
involves much more than Django, so advanced topics including REST, testing,
debugging, security, and deployment are also explored in detail in this module.

What you need for this learning path


To develop with Django 1.8, you will need Python 2.7 or Python 3.4, the Pillow
library for image manipulation, the MySQL database and MySQLdb bindings or
PostgreSQL database, virtualenv to keep each project's Python modules separated,
and Git or Subversion for version control.

The other software required for Django development are as follows:

PIP 1.5
Text editor (or a Python IDE)
Web browser (the latest version, please)

For Module 3, Django Design Patterns and Best Practices, it is recommend to work 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.

Certain chapters might also require installing certain Python libraries or Django
packages. They will be mentioned as, saythe factory_boy package. In most cases,
they can be installed using pip as follows:
$ pip install factory_boy

+HQFHLWLVKLJKO\UHFRPPHQGHGWKDW\RXUVWFUHDWHDVHSDUDWHYLUWXDOHQYLURQPHQW
as mentioned in Module 3, Chapter 2, Application Design.

[ ii ]
Preface

Who this learning path is for


Web developers who want to use modern Python-based web frameworks like Django
to build powerful web applications. The course is mostly self-contained and introduces
web development with Python to a reader who is familiar with web development
concepts and can help him become an expert in this trade. It's intended for all levels of
web developers, both students and practitioners from novice to experts.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this coursewhat 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 feedback@packtpub.com, and mention


the title of the course 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 any of our product, see our author guide at www.packtpub.com/
authors.

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

Downloading the example code


<RXFDQGRZQORDGWKHH[DPSOHFRGHOHVIRUWKLVFRXUVHIURP\RXUDFFRXQWDW
http://www.packtpub.com. If you purchased this course elsewhere, you can
visit http://www.packtpub.com/supportDQGUHJLVWHUWRKDYHWKHOHVHPDLOHG
directly to you.

<RXFDQGRZQORDGWKHFRGHOHVE\IROORZLQJWKHVHVWHSV

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the course in the Search box.

[ iii ]
Preface

5. 6HOHFWWKHFRXUVHIRUZKLFK\RX
UHORRNLQJWRGRZQORDGWKHFRGHOHV
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

<RXFDQDOVRGRZQORDGWKHFRGHOHVE\FOLFNLQJRQWKHCode Files button on the


course's webpage at the Packt Publishing website. This page can be accessed by
entering the course's name in the Search box. Please note that you need to be logged
into your Packt account.

2QFHWKHOHLVGRZQORDGHGSOHDVHPDNHVXUHWKDW\RXXQ]LSRUH[WUDFWWKHIROGHU
using the latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the course is also hosted on GitHub at https://github.com/
PacktPublishing/Django-Web-Development-with-Python.We also have other
code bundles from our rich catalog of books and videos available at https://
github.com/PacktPublishing/. Check them out!

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
GRKDSSHQ,I\RXQGDPLVWDNHLQRQHRIRXUERRNVFRXUVHVPD\EHDPLVWDNHLQ
the text or the codewe 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
YHUVLRQVRIWKLVFRXUVH,I\RXQGDQ\HUUDWDSOHDVHUHSRUWWKHPE\YLVLWLQJhttp://
www.packtpub.com/submit-errata, selecting your course, clicking on the Errata
Submission Form link, and entering the details of your errata. Once your errata are
YHULHG\RXUVXEPLVVLRQZLOOEHDFFHSWHGDQGWKHHUUDWDZLOOEHXSORDGHGWRRXU
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/supportDQGHQWHUWKHQDPHRIWKHERRNLQWKHVHDUFKHOG7KHUHTXLUHG
information will appear under the Errata section.

[ iv ]
Preface

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 copyright@packtpub.com 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 course, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.

[v]
Module 1 1
Chapter 1: Django's Position on the Web 3
From Web 1.0 to Web 2.0 3
What is Django? 5
The MVC framework 5
Why use Django? 7
Summary 8
Chapter 2: Creating a Django Project 9
Installing Python 3 9
Installing setuptools 11
Installing PIP 12
Installing Django 13
Starting your project with Django 14
Creating an application 15
&RQJXULQJWKHDSSOLFDWLRQ 
Summary 17
Chapter 3: Hello World! with Django 19
Routing in Django 19
Regular expressions 21
&UHDWLQJRXUUVW85/ 
&UHDWLQJRXUUVWYLHZ 
Testing our application 27
Summary 27
Chapter 4: Working with Templates 29
Displaying Hello world! in a template 29
Injecting the data from the view to the template 31
Creating dynamic templates 31

[i]
Table of Contents

Integrating variables in templates 32


8VLQJOWHUV 
&UHDWLQJ'5<85/V 
Extending the templates 38
8VLQJVWDWLFOHVLQWHPSODWHV 
Summary 40
Chapter 5: Working with Models 41
Databases and Django 42
Migrations with South 42
Creating simple models 44
7KHUHODWLRQVKLSEHWZHHQWKHPRGHOV 
Extending models 47
The admin module 49
Advanced usage of models 52
Summary 53
&KDSWHUGetting a Model's Data with Querysets 55
The persisting model's data on the database 55
*HWWLQJGDWDIURPWKHGDWDEDVH 
8VLQJWKHJHWSDUDPHWHU 
6DYLQJWKHIRUHLJQNH\ 
8SGDWLQJUHFRUGVLQWKHGDWDEDVH 
'HOHWLQJDUHFRUG 
*HWWLQJOLQNHGUHFRUGV 
$GYDQFHGXVDJHRIWKHTXHU\VHW 
6XPPDU\ 
Chapter 7: :RUNLQJZLWK'MDQJR)RUPV 
$GGLQJDGHYHORSHUZLWKRXWXVLQJ'MDQJRIRUPV 
Adding a developer with Django forms 71
The form based on a model 75
$GYDQFHGXVDJHRI'MDQJRIRUPV 
Summary 80
Chapter 8: Raising Your Productivity with CBV 81
The CreateView CBV 82
:RUNLQJZLWK/LVW9LHZ 
The DetailView CBV 87
7KH8SGDWH9LHZ&%9 
The DeleteView CBV 92
Going further by extending the CBV 93
Summary 95

[ ii ]
Table of Contents

Chapter 9: 8VLQJ6HVVLRQV 
Creating and getting session variables 99
About session security 102
Summary 103
Chapter 10: The Authentication Module 105
How to use the authentication module 105
Adding a user 107
/RJLQDQGORJRXWSDJHV 
Restricting access to the connected members 113
Summary 114
Chapter 11: 8VLQJ$-$;ZLWK'MDQJR 
Working with jQuery 115
M4XHU\EDVLFV 
:RUNLQJZLWK$-$;LQWKHWDVNPDQDJHU 
Summary 121
Chapter 12: Production with Django 123
Completing the development 123
Selecting the physical server 124
Selecting the server software 124
Selecting the server database 125
'HSOR\LQJWKH'MDQJRZHEVLWH 
Installing Django, South, Gunicorn, and psycopg2 127
Summary 131
Appendix: Cheatsheet 133
7KHHOGW\SHVLQPRGHOV 
7KHIRUPHOGV 
The template language 138
Module 2 143
Chapter 1: Getting Started with Django 1.8 145
:RUNLQJZLWKDYLUWXDOHQYLURQPHQW 
&UHDWLQJDSURMHFWOHVWUXFWXUH 
Handling project dependencies with pip 151
Making your code compatible with both Python 2.7 and Python 3 153
,QFOXGLQJH[WHUQDOGHSHQGHQFLHVLQ\RXUSURMHFW 
&RQJXULQJVHWWLQJVIRUGHYHORSPHQWWHVWLQJVWDJLQJDQG
production 158
environments 158
'HQLQJUHODWLYHSDWKVLQWKHVHWWLQJV 
&UHDWLQJDQGLQFOXGLQJORFDOVHWWLQJV 

[ iii ]
Table of Contents

6HWWLQJXS67$7,&B85/G\QDPLFDOO\IRU6XEYHUVLRQXVHUV 
6HWWLQJXS67$7,&B85/G\QDPLFDOO\IRU*LWXVHUV 
6HWWLQJ87)DVWKHGHIDXOWHQFRGLQJIRU0\64/FRQJXUDWLRQ 
6HWWLQJWKH6XEYHUVLRQLJQRUHSURSHUW\ 
&UHDWLQJWKH*LWLJQRUHOH 
'HOHWLQJ3\WKRQFRPSLOHGOHV 
5HVSHFWLQJWKHLPSRUWRUGHULQ3\WKRQOHV 
&UHDWLQJDSSFRQJXUDWLRQ 
'HQLQJRYHUZULWDEOHDSSVHWWLQJV 
Chapter 2: Database Structure 179
8VLQJPRGHOPL[LQV 
&UHDWLQJDPRGHOPL[LQZLWK85/UHODWHGPHWKRGV 
&UHDWLQJDPRGHOPL[LQWRKDQGOHFUHDWLRQDQGPRGLFDWLRQGDWHV 
&UHDWLQJDPRGHOPL[LQWRWDNHFDUHRIPHWDWDJV 
Creating a model mixin to handle generic relations 189
+DQGOLQJPXOWLOLQJXDOHOGV 
8VLQJPLJUDWLRQV 
Switching from South migrations to Django migrations 202
&KDQJLQJDIRUHLJQNH\WRWKHPDQ\WRPDQ\HOG 
Chapter 3: Forms and Views 207
Passing HttpRequest to the form 208
8WLOL]LQJWKHVDYHPHWKRGRIWKHIRUP 
8SORDGLQJLPDJHV 
&UHDWLQJDIRUPOD\RXWZLWKGMDQJRFULVS\IRUPV 
'RZQORDGLQJDXWKRUL]HGOHV 
Filtering object lists 227
Managing paginated lists 235
&RPSRVLQJFODVVEDVHGYLHZV 
Generating PDF documents 242
Implementing a multilingual search with Haystack 249
Chapter 4: 7HPSODWHVDQG-DYD6FULSW 
$UUDQJLQJWKHEDVHKWPOWHPSODWH 
,QFOXGLQJ-DYD6FULSWVHWWLQJV 
8VLQJ+70/GDWDDWWULEXWHV 
Opening object details in a modal dialog 271
,PSOHPHQWLQJDFRQWLQXRXVVFUROO 
,PSOHPHQWLQJWKH/LNHZLGJHW 
8SORDGLQJLPDJHVE\$MD[ 

[ iv ]
Table of Contents

Chapter 5: Custom Template Filters and Tags 295


)ROORZLQJFRQYHQWLRQVIRU\RXURZQWHPSODWHOWHUVDQGWDJV 
&UHDWLQJDWHPSODWHOWHUWRVKRZKRZPDQ\GD\VKDYHSDVVHG
since a post was 297
published 297
&UHDWLQJDWHPSODWHOWHUWRH[WUDFWWKHUVWPHGLDREMHFW 
&UHDWLQJDWHPSODWHOWHUWRKXPDQL]H85/V 
Creating a template tag to include a template if it exists 302
&UHDWLQJDWHPSODWHWDJWRORDGD4XHU\6HWLQDWHPSODWH 
Creating a template tag to parse content as a template 310
Creating a template tag to modify request query parameters 313
&KDSWHUModel Administration 319
&XVWRPL]LQJFROXPQVRQWKHFKDQJHOLVWSDJH 
Creating admin actions 324
'HYHORSLQJFKDQJHOLVWOWHUV 
&XVWRPL]LQJGHIDXOWDGPLQVHWWLQJV 
,QVHUWLQJDPDSLQWRDFKDQJHIRUP 
Chapter 7: Django CMS 349
Creating templates for Django CMS 350
Structuring the page menu 354
Converting an app to a CMS app 358
$WWDFKLQJ\RXURZQQDYLJDWLRQ 
:ULWLQJ\RXURZQ&06SOXJLQ 
$GGLQJQHZHOGVWRWKH&06SDJH 
Chapter 8: Hierarchical Structures 375
Creating hierarchical categories 377
&UHDWLQJDFDWHJRU\DGPLQLVWUDWLRQLQWHUIDFHZLWKGMDQJRPSWWDGPLQ 
Creating a category administration interface with
GMDQJRPSWWWUHHHGLWRU 
Rendering categories in a template 387
8VLQJDVLQJOHVHOHFWLRQHOGWRFKRRVHDFDWHJRU\LQIRUPV 
8VLQJDFKHFNER[OLVWWRFKRRVHPXOWLSOHFDWHJRULHVLQIRUPV 
Chapter 9: Data Import and Export 397
,PSRUWLQJGDWDIURPDORFDO&69OH 
,PSRUWLQJGDWDIURPDORFDO([FHOOH 
,PSRUWLQJGDWDIURPDQH[WHUQDO-621OH 
,PSRUWLQJGDWDIURPDQH[WHUQDO;0/OH 
&UHDWLQJOWHUDEOH566IHHGV 

[v]
Table of Contents

8VLQJ7DVW\SLHWRFUHDWH$3, 
8VLQJ'MDQJR5(67IUDPHZRUNWRFUHDWH$3, 
Chapter 10: Bells and Whistles 429
8VLQJWKH'MDQJRVKHOO 
8VLQJGDWDEDVHTXHU\H[SUHVVLRQV 
0RQNH\SDWFKLQJWKHVOXJLI\ IXQFWLRQIRUEHWWHULQWHUQDWLRQDOL]DWLRQ
support 439
Toggling the Debug Toolbar 442
8VLQJ7KUHDG/RFDO0LGGOHZDUH 
Caching the method return value 448
8VLQJ0HPFDFKHGWRFDFKH'MDQJRYLHZV 
8VLQJVLJQDOVWRQRWLI\DGPLQLVWUDWRUVDERXWQHZHQWULHV 
Checking for missing settings 454
Chapter 11: Testing and Deployment 457
Testing pages with Selenium 458
7HVWLQJYLHZVZLWKPRFN 
7HVWLQJ$3,FUHDWHGXVLQJ'MDQJR5(67IUDPHZRUN 
Releasing a reusable Django app 473
*HWWLQJGHWDLOHGHUURUUHSRUWLQJYLDHPDLO 
Deploying on Apache with mod_wsgi 479
6HWWLQJXSFURQMREVIRUUHJXODUWDVNV 
Creating and using the Fabric deployment script 489
Module 3 501
Chapter 1: Django and Patterns 503
How does Django work to? 507
What is a Pattern? 508
Patterns in this book 513
Best practices 514
Summary 515
Chapter 2: Application Design 517
How to gather requirements 517
Are you a story teller? 519
+70/PRFNXSV 
Designing the application 521
Before starting the project 523
SuperBook your mission, should you choose to accept it 524
6XPPDU\ 

[ vi ]
Table of Contents

Chapter 3: Models 527


M is bigger than V and C 527
The model hunt 529
Structural patterns 531
5HWULHYDOSDWWHUQV 
Migrations 552
Summary 552
Chapter 4: 9LHZVDQG85/V 
A view from the top 553
&ODVVEDVHGJHQHULFYLHZV 
View mixins 558
'HFRUDWRUV 
9LHZSDWWHUQV 
'HVLJQLQJ85/V 
Summary 574
Chapter 5: Templates 575
8QGHUVWDQGLQJ'MDQJR
VWHPSODWHODQJXDJHIHDWXUHV 
2UJDQL]LQJWHPSODWHV 
8VLQJ%RRWVWUDS 
Template patterns 583
Summary 587
&KDSWHUAdmin Interface 589
Enhancing models for the admin 592
$GPLQLQWHUIDFHFXVWRPL]DWLRQV 
Protecting the admin 599
6XPPDU\ 
Chapter 7: )RUPV 
+RZIRUPVZRUN 
'LVSOD\LQJIRUPV 
8QGHUVWDQGLQJ&65) 
)RUPSURFHVVLQJZLWK&ODVVEDVHGYLHZV 
)RUPSDWWHUQV 
6XPPDU\ 
Chapter 8: 'HDOLQJZLWK/HJDF\&RGH 
)LQGLQJWKH'MDQJRYHUVLRQ 
:KHUHDUHWKHOHV"7KLVLVQRW3+3 
6WDUWLQJZLWKXUOVS\ 
-XPSLQJDURXQGWKHFRGH 
8QGHUVWDQGLQJWKHFRGHEDVH 

[ vii ]
Table of Contents

,QFUHPHQWDOFKDQJHRUDIXOOUHZULWH" 
:ULWHWHVWVEHIRUHPDNLQJDQ\FKDQJHV 
/HJDF\GDWDEDVHV 
6XPPDU\ 
Chapter 9: 7HVWLQJDQG'HEXJJLQJ 
:K\ZULWHWHVWV" 
7HVWGULYHQGHYHORSPHQW 
:ULWLQJDWHVWFDVH 
0RFNLQJ 
3DWWHUQWHVW[WXUHVDQGIDFWRULHV 
/HDUQLQJPRUHDERXWWHVWLQJ 
'HEXJJLQJ 
7KHSULQWIXQFWLRQ 
/RJJLQJ 
7KH'MDQJR'HEXJ7RROEDU 
7KH3\WKRQGHEXJJHUSGE 
2WKHUGHEXJJHUV 
'HEXJJLQJ'MDQJRWHPSODWHV 
6XPPDU\ 
Chapter 10: 6HFXULW\ 
&URVVVLWHVFULSWLQJ ;66  
$KDQG\VHFXULW\FKHFNOLVW 
6XPPDU\ 
Chapter 11: 3URGXFWLRQUHDG\ 
3URGXFWLRQHQYLURQPHQW 
+RVWLQJ 
'HSOR\PHQWWRROV 
0RQLWRULQJ 
3HUIRUPDQFH 
6XPPDU\ 
Appendix: 3\WKRQYHUVXV3\WKRQ 
%XW,VWLOOXVH3\WKRQ 
3\WKRQ 
)XUWKHULQIRUPDWLRQ 
%LEOLRJUDSK\ 

[ viii ]