Django: Web Development with Python - Samuel Dauzon - E-Book

Django: Web Development with Python E-Book

Samuel Dauzon

0,0
70,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

From an idea to a prototype – a complete guide for web development with the Django framework

About This Book

  • Explore the best practices to develop applications of a superior quality with Django framework
  • Unravel the common problems of web development in Django
  • This course teaches you major Django functions and will help you improve your skills by developing models, forms, views, and templates
  • Experience the challenges of working on an end-to-end social network project

Who This Book 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.

What You Will Learn

  • Use Django models to store information in the database and generate queries to access a database across models
  • Quickly develop web pages to create, read, update, and delete data from the model using class-based views
  • Generate very maintainable forms with Django
  • Import data from local sources and external web services as well as exporting your data to third parties
  • Deep dive into various aspects of Django from models and views to testing and deployment
  • Familiarize yourself with the various nuances of web development such as browser attacks and databases

In Detail

Data science is hot right now, and the need for multitalented 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 your career as an entrepreneur or web developer. Django is a web framework that was designed to strike a balance between rapid web development and high performance. This course will take you on a journey to become an efficient web developer thoroughly understanding the key concepts of Django framework. This learning path is divided into three modules. The course begins with basic concepts of the Django framework. The first module, Django Essentials, is like a practical guide, filled with many real-world examples to build highly effective Django web application. After getting familiar with core concepts of Django, it's time to practice your learning from the first module with the help of over 90 recipes available in this module. In the second module, Web Development with Django Cookbook, you'll learn varying complexities to help you create multilingual, responsive, and scalable websites with Django. By the end of this module, you will have a good understanding of the new features added to Django 1.8 and be an expert at web development processes.The next step is to discover the latest best practices and idioms in this rapidly evolving Django framework. This is what you'll be learning in our third module, Django Design Patterns and Best Practices. This module will teach you common design patterns to develop better Django code. By the end of the module, you will be able to leverage the Django framework to develop a fully functional web application with minimal effort.

Style and approach

This course includes all the resources that will help you jump into the web development field with Django and learn how to make scalable and robust web applications. The aim is to create a smooth learning path that will teach you how to get started with the powerful Django framework and perform various web development techniques in depth. Through this comprehensive course, you'll learn web development with Django from scratch to finish!

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 788

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Django: Web Development with Python
Django: Web Development with Python
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Django's Position on the Web
From Web 1.0 to Web 2.0
Web 1.0
Web 2.0
What is Django?
Django – a web framework
The MVC framework
Why use Django?
Summary
2. Creating a Django Project
Installing Python 3
Installing Python 3 for Windows
Installing Python 3 for Linux
Installing Python 3 for Mac OS
Installing setuptools
Installing setuptools for Windows
Installing setuptools for Linux
Installing setuptools for Mac OS
Installing PIP
Installing PIP for Windows
Installing PIP for Linux
Installing PIP for Mac OS
Installing Django
Installing Django for Windows
Installing Django for Linux
Installing Django for Mac OS
Starting your project with Django
Creating an application
Configuring the application
Summary
3. Hello World! with Django
Routing in Django
Regular expressions
The uninterpreted characters
The beginning and the end of the line
The any character regular expression
Character classes
Validating the number of characters
Creating our first URL
Creating our first view
Testing our application
Summary
4. Working with Templates
Displaying Hello world! in a template
Injecting the data from the view to the template
Creating dynamic templates
Integrating variables in templates
Conditional statements
Looping in a template
Using filters
The upper and lower filters
The lower filter
The upper filter
The capfirst filter
The pluralize filter
The escape and safe to avoid XSS filters
The linebreaks filter
The truncatechars filter
Creating DRY URLs
Extending the templates
Using static files in templates
Summary
5. Working with Models
Databases and Django
Migrations with South
Installing South
Using the South extension
Creating simple models
The UserProfile model
The Project model
The relationship between the models
Creating the task model with relationships
Extending models
The admin module
Installing the module
Using the module
Advanced usage of models
Using two relationships for the same model
Defining the str method
Summary
6. Getting a Model's Data with Querysets
The persisting model's data on the database
Filling a model and saving it in the database
Getting data from the database
Getting multiple records
Getting only one record
Getting a model instance from the queryset instance
Using the get parameter
Saving the foreign key
Updating records in the database
Updating a model instance
Updating multiple records
Deleting a record
Getting linked records
Advanced usage of the queryset
Using an OR operator in a queryset
Using the lower and greater than lookups
Performing an exclude query
Making a raw SQL query
Summary
7. Working with Django Forms
Adding a developer without using Django forms
Template of an HTML form
The view using the POST data reception
Adding a developer with Django forms
CSRF protection
The view with a Django form
Template of a Django form
The form based on a model
The supervisor creation form
Advanced usage of Django forms
Extending the validation form
Customizing the display of errors
Using widgets
Setting initial data in a form
When instantiating the form
When defining fields
Summary
8. Raising Your Productivity with CBV
The CreateView CBV
An example of minimalist usage
Working with ListView
An example of minimalist usage
Extending ListView
The DetailView CBV
An example of minimalist usage
Extending DetailView
The UpdateView CBV
An example of minimalist usage
Extending the UpdateView CBV
The DeleteView CBV
Going further by extending the CBV
Using a custom class CBV update
Summary
9. Using Sessions
Creating and getting session variables
An example – showing the last task consulted
About session security
Summary
10. The Authentication Module
How to use the authentication module
Configuring the Django application
Editing the UserProfile model
Adding a user
Login and logout pages
Restricting access to the connected members
Restricting access to views
Restricting access to URLs
Summary
11. Using AJAX with Django
Working with jQuery
jQuery basics
CSS selectors in jQuery
Getting back the HTML content
Setting HTML content in an element
Looping elements
Importing the jQuery library
Working with AJAX in the task manager
Summary
12. Production with Django
Completing the development
Selecting the physical server
Selecting the server software
Selecting the server database
Deploying the Django website
Installing PIP and Python 3
Installing PostgreSQL
Installing virtualenv and creating a virtual environment
Installing Django, South, Gunicorn, and psycopg2
Configuring PostgreSQL
Adaptation of Work_manager to production
Initial South migration
Using Gunicorn
Starting Nginx
Summary
A. Cheatsheet
The field types in models
The numerical field type
The string field type
The temporal field type
Other types of fields
Relationship between models
The model meta attributes
Options common to all fields of models
The form fields
Common options for the form fields
The widget form
Error messages (forms and models)
The template language
Template tags
Loops in dictionaries
Conditional statements
The template filters
The queryset methods
2. Module 2
1. Getting Started with Django 1.8
Introduction
Working with a virtual environment
Getting ready
How to do it…
How it works…
See also
Creating a project file structure
Getting ready
How to do it…
How it works…
See also
Handling project dependencies with pip
Getting ready
How to do it…
How it works…
There's more…
See also
Making your code compatible with both Python 2.7 and Python 3
Getting ready
How to do it…
How it works…
Including external dependencies in your project
Getting ready
How to do it…
How it works…
See also
Configuring settings for development, testing, staging, and production environments
Getting ready
How to do it…
How it works…
See also
Defining relative paths in the settings
Getting ready
How to do it…
How it works…
See also
Creating and including local settings
Getting ready
How to do it…
How it works…
See also
Setting up STATIC_URL dynamically for Subversion users
Getting ready
How to do it…
How it works…
See also
Setting up STATIC_URL dynamically for Git users
Getting ready
How to do it…
How it works…
See also
Setting UTF-8 as the default encoding for MySQL configuration
Getting ready
How to do it…
How it works…
Setting the Subversion ignore property
Getting ready
How to do it…
How it works…
See also
Creating the Git ignore file
Getting ready
How to do it…
How it works…
See also
Deleting Python-compiled files
Getting ready
How to do it…
How it works…
See also
Respecting the import order in Python files
Getting ready
How to do it…
How it works…
There's more…
See also
Creating app configuration
Getting ready
How to do it…
How it works…
There is more…
See also
Defining overwritable app settings
Getting ready
How to do it…
How it works…
2. Database Structure
Introduction
Using model mixins
Getting ready
How to do it…
How it works…
There's more…
See also
Creating a model mixin with URL-related methods
Getting ready
How to do it…
How it works…
See also
Creating a model mixin to handle creation and modification dates
Getting ready
How to do it…
How it works…
See also
Creating a model mixin to take care of meta tags
Getting ready
How to do it…
How it works…
See also
Creating a model mixin to handle generic relations
Getting ready
How to do it…
How it works…
See also
Handling multilingual fields
Getting ready
How to do it…
How it works…
Using migrations
Getting ready
How to do it…
How it works…
See also
Switching from South migrations to Django migrations
Getting ready
How to do it…
How it works…
See also
Changing a foreign key to the many-to-many field
Getting ready
How to do it…
How it works…
See also
3. Forms and Views
Introduction
Passing HttpRequest to the form
Getting ready
How to do it…
How it works…
See also
Utilizing the save method of the form
Getting ready
How to do it…
How it works…
See also
Uploading images
Getting ready
How to do it…
How it works…
There's more
See also
Creating a form layout with django-crispy-forms
Getting ready
How to do it…
How it works…
There's more…
See also
Downloading authorized files
Getting ready
How to do it…
How it works…
See also
Filtering object lists
Getting ready
How to do it…
How it works…
See also
Managing paginated lists
Getting ready
How to do it…
How it works…
See also
Composing class-based views
Getting ready
How to do it…
How it works…
There's more…
See also
Generating PDF documents
Getting ready
How to do it…
How it works…
See also
Implementing a multilingual search with Haystack
Getting ready
How to do it…
How it works…
See also
4. Templates and JavaScript
Introduction
Arranging the base.html template
Getting ready
How to do it…
How it works…
See also
Including JavaScript settings
Getting ready
How to do it…
How it works…
See also
Using HTML5 data attributes
Getting ready
How to do it…
How it works…
See also
Opening object details in a modal dialog
Getting ready
How to do it…
How it works…
See also
Implementing a continuous scroll
Getting ready
How to do it…
How it works…
See also
Implementing the Like widget
Getting ready
How to do it…
How it works…
See also
Uploading images by Ajax
Getting ready
How to do it…
How it works…
See also
5. Custom Template Filters and Tags
Introduction
Following conventions for your own template filters and tags
How to do it...
Creating a template filter to show how many days have passed since a post was published
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a template filter to extract the first media object
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a template filter to humanize URLs
Getting ready
How to do it...
How it works...
See also
Creating a template tag to include a template if it exists
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a template tag to load a QuerySet in a template
Getting ready
How to do it...
How it works...
See also
Creating a template tag to parse content as a template
Getting ready
How to do it...
How it works...
See also
Creating a template tag to modify request query parameters
Getting ready
How to do it...
How it works...
See also
6. Model Administration
Introduction
Customizing columns on the change list page
Getting ready
How to do it...
How it works...
There's more...
See also
Creating admin actions
Getting ready
How to do it...
How it works...
See also
Developing change list filters
Getting ready
How to do it...
How it works...
See also
Customizing default admin settings
Getting ready
How to do it...
How it works...
There's more...
See also
Inserting a map into a change form
Getting ready
How to do it...
How it works...
See also
7. Django CMS
Introduction
Creating templates for Django CMS
Getting ready
How to do it...
How it works...
See also
Structuring the page menu
Getting ready
How to do it...
How it works...
See also
Converting an app to a CMS app
Getting ready
How to do it...
How it works...
See also
Attaching your own navigation
Getting ready
How to do it...
How it works...
See also
Writing your own CMS plugin
Getting ready
How to do it...
How it works...
See also
Adding new fields to the CMS page
Getting ready
How to do it...
How it works...
See also
8. Hierarchical Structures
Introduction
Creating hierarchical categories
Getting ready
How to do it...
How it works...
See also
Creating a category administration interface with django-mptt-admin
Getting ready
How to do it...
How it works...
See also
Creating a category administration interface with django-mptt-tree-editor
Getting ready
How to do it...
How it works...
See also
Rendering categories in a template
Getting ready
How to do it...
How it works...
There's more...
See also
Using a single selection field to choose a category in forms
Getting ready
How to do it...
How it works...
See also
Using a checkbox list to choose multiple categories in forms
Getting ready
How to do it...
How it works...
See also
9. Data Import and Export
Introduction
Importing data from a local CSV file
Getting ready
How to do it...
How it works...
There's more...
See also
Importing data from a local Excel file
Getting ready
How to do it...
How it works...
There's more...
See also
Importing data from an external JSON file
Getting ready
How to do it...
How it works...
See also
Importing data from an external XML file
Getting ready
How to do it...
How it works...
There's more...
See also
Creating filterable RSS feeds
Getting ready
How to do it...
How it works...
See also
Using Tastypie to create API
Getting ready
How to do it...
How it works...
See also
Using Django REST framework to create API
Getting ready
How to do it...
How it works...
See also
10. Bells and Whistles
Introduction
Using the Django shell
Getting ready
How to do it...
How it works...
See also
Using database query expressions
Getting ready
How to do it...
How it works...
See also
Monkey-patching the slugify() function for better internationalization support
Getting ready
How to do it...
How it works...
There's more...
See also
Toggling the Debug Toolbar
Getting ready
How to do it...
How it works...
See also
Using ThreadLocalMiddleware
Getting ready
How to do it...
How it works...
See also
Caching the method return value
Getting ready
How to do it...
How it works...
See also
Using Memcached to cache Django views
Getting ready
How to do it...
How it works...
See also
Using signals to notify administrators about new entries
Getting ready
How to do it...
How it works...
See also
Checking for missing settings
Getting ready
How to do it...
How it works...
See also
11. Testing and Deployment
Introduction
Testing pages with Selenium
Getting ready
How to do it...
How it works...
See also
Testing views with mock
Getting ready
How to do it...
How it works...
See also
Testing API created using Django REST framework
Getting ready
How to do it...
How it works...
See also
Releasing a reusable Django app
Getting ready
How to do it...
How it works...
See also
Getting detailed error reporting via e-mail
Getting ready
How to do it...
How it works...
See also
Deploying on Apache with mod_wsgi
Getting ready
How to do it...
How it works...
There's more...
See also
Setting up cron jobs for regular tasks
Getting ready
How to do it...
How it works...
See also
Creating and using the Fabric deployment script
Getting ready
How to do it...
How it works...
There's more...
See also
3. Module 3
1. Django and Patterns
How does Django work to?
What is a Pattern?
Gang of Four Patterns
Is Django MVC?
Fowler's Patterns
Are there more patterns?
Patterns in this book
Criticism of Patterns
How to use Patterns
Best practices
Python Zen and Django's design philosophy
Summary
2. Application Design
How to gather requirements
Are you a story teller?
HTML mockups
Designing the application
Dividing a project into Apps
Reuse or roll-your-own?
My app sandbox
Which packages made it?
Before starting the project
SuperBook – your mission, should you choose to accept it
Why Python 3?
Starting the project
Summary
3. Models
M is bigger than V and C
The model hunt
Splitting models.py into multiple files
Structural patterns
Patterns – normalized models
Problem details
Solution details
Three steps of normalization
First normal form (1NF)
Second normal form or 2NF
Third normal form or 3NF
Django models
Performance and denormalization
Should we always normalize?
Pattern – model mixins
Problem details
Solution details
Model mixins
Pattern – user profiles
Problem details
Solution details
Signals
Admin
Multiple profile types
Pattern – service objects
Problem details
Solution details
Retrieval patterns
Pattern – property field
Problem details
Solution details
Cached properties
Pattern – custom model managers
Problem details
Solution details
Set operations on QuerySets
Chaining multiple QuerySets
Migrations
Summary
4. Views and URLs
A view from the top
Views got classier
Class-based generic views
View mixins
Order of mixins
Decorators
View patterns
Pattern – access controlled views
Problem details
Solution details
Pattern – context enhancers
Problem details
Solution details
Pattern – services
Problem details
Solution details
Designing URLs
URL anatomy
What happens in urls.py?
The URL pattern syntax
Mnemonic – parents question pink action-figures
Names and namespaces
Pattern order
URL pattern styles
Departmental store URLs
RESTful URLs
Summary
5. Templates
Understanding Django's template language features
Variables
Attributes
Filters
Tags
Philosophy – don't invent a programming language
Organizing templates
Support for other template languages
Using Bootstrap
But they all look the same!
Template patterns
Pattern – template inheritance tree
Problem details
Solution details
Pattern – the active link
Problem details
Solution details
A template-only solution
Custom tags
Summary
6. Admin Interface
Using the admin interface
Enhancing models for the admin
Not everyone should be an admin
Admin interface customizations
Changing the heading
Changing the base and stylesheets
Adding a Rich Text Editor for WYSIWYG editing
Bootstrap-themed admin
Complete overhauls
Protecting the admin
Pattern – feature flags
Problem details
Solution details
Summary
7. Forms
How forms work
Forms in Django
Why does data need cleaning?
Displaying forms
Time to be crisp
Understanding CSRF
Form processing with Class-based views
Form patterns
Pattern – dynamic form generation
Problem details
Solution details
Pattern – user-based forms
Problem details
Solution details
Pattern – multiple form actions per view
Problem details
Solution details
Separate views for separate actions
Same view for separate actions
Pattern – CRUD views
Problem details
Solution details
Summary
8. Dealing with Legacy Code
Finding the Django version
Activating the virtual environment
Where are the files? This is not PHP
Starting with urls.py
Jumping around the code
Understanding the code base
Creating the big picture
Incremental change or a full rewrite?
Write tests before making any changes
Step-by-step process to writing tests
Legacy databases
Summary
9. Testing and Debugging
Why write tests?
Test-driven development
Writing a test case
The assert method
Writing better test cases
Mocking
Pattern – test fixtures and factories
Problem details
Solution details
Learning more about testing
Debugging
Django debug page
A better debug page
The print function
Logging
The Django Debug Toolbar
The Python debugger pdb
Other debuggers
Debugging Django templates
Summary
10. Security
Cross-site scripting (XSS)
Why are your cookies valuable?
How Django helps
Where Django might not help
Cross-Site Request Forgery (CSRF)
How Django helps
Where Django might not help
SQL injection
How Django helps
Where Django might not help
Clickjacking
How Django helps
Shell injection
How Django helps
And the list goes on
A handy security checklist
Summary
11. Production-ready
Production environment
Choosing a web stack
Components of a stack
Hosting
Platform as a service
Virtual private servers
Other hosting approaches
Deployment tools
Fabric
Typical deployment steps
Configuration management
Monitoring
Performance
Frontend performance
Backend performance
Templates
Database
Caching
Cached session backend
Caching frameworks
Caching patterns
Summary
A. Python 2 versus Python 3
But I still use Python 2.7!
Python 3
Python 3 for Djangonauts
Change all the __unicode__ methods into __str__
All classes inherit from the object class
Calling super() is easier
Relative imports must be explicit
HttpRequest and HttpResponse have str and bytes types
Exception syntax changes and improvements
Standard library reorganized
New goodies
Using Pyvenv and Pip
Other changes
Further information
A. Bibliography
Index

Django: Web Development with Python

Django: Web Development with Python

From an idea to a prototype – a complete guide for 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: September 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

Samuel Dauzon

Aidas Bendoraitis

Arun Ravindran

Reviewers

Jorge Armin Garcia Lopez

Caleb Smith

Deepak Thukral

Patrick Chan

Jake Kronika

Jorge Armin Garcia Lopez

Shoubhik Bose

Kracekumar Ramaraju

Jai Vikram Singh Verma

Content Development Editor

Priyanka Mehta

Graphics

Disha Haria

Production Coordinator

Aparna Bhagat

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 development has become more efficient and has improved in quality. Django 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. Django has an established and vibrant community, where you can find source code, 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.

What this learning path covers

Module 1, Django Essentials, a practical guide, filled with many real world examples to 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.5Text 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, say—the factory_boy package. In most cases, they can be installed using pip as follows:

$ pip install factory_boy

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

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 course—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 send an e-mail to <[email protected]>, 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

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

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the course in the Search box.Select the course for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code 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.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-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 do happen. If you find a mistake in one of our books/courses—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 course. If you find any errata, please report them by visiting http://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 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 course, you can contact us at <[email protected]>, and we will do our best to address the problem.

Part 1. Module 1

Django Essentials

Develop simple web applications with the powerful Django framework

Chapter 1. Django's Position on the Web

Web development has significantly evolved in recent years, particularly with the apparition of web frameworks. We will learn how to use the Django framework to create a complete website.

In this chapter, we will discuss the following:

The changes in the WebA presentation of DjangoMVC development pattern

From Web 1.0 to Web 2.0

The Web that you see today has not always been as it appears today. Indeed, many technologies such as CSS, AJAX, or the new HTML 5 version have improved the Web.

Web 1.0

The Web was born 25 years ago, thanks to growing new technologies. Two of these have been very decisive:

The HTML language is a display language. It allows you to organize information with nested tags.The HTTP protocol is a communication network protocol that allows a client and a server to communicate. The client is often a browser such as Firefox or Google Chrome, and the server is very often a web server such as Nginx, Apache, or Microsoft IIS.

In the beginning, developers used the <table> tag to organize various elements of their page as the menu, header, or content. The images displayed on the web pages were of low resolutions to avoid the risk of making the page heavy. The only action that users could perform was to click on the hypertext links to navigate to other pages.

These hypertext links enabled users to navigate from one page to another by sending only one type of data: the URL of the page. The Uniform Resource Locator (URL) defines a unique link to get resources such as an HTML page, picture, or PDF file. No data other than the URL was sent by the user.

Web 2.0

The term Web 2.0 was coined by Dale Dougherty, O'Reilly Media Company, and was mediated in October 2004 by Tim O'Reilly during the first Web 2.0 conference.

This new Web became interactive and reachable to beginners. It came as a gift to many technologies, including the following:

The server-side languages such as PHP, Java Server Page (JSP), or ASP. These languages allow you to communicate with a database to deliver dynamic content. This also allows users to send data in HTML forms in order to process data using the web server. Databases store a lot of information. This information can be used to authenticate a user or display an item list from older to more recent entries.Client-side script such as JavaScript enables users to perform simple tasks without refreshing the page. Asynchronous JavaScript and XML (AJAX) brings an important feature to the current Web: asynchronous swapping between the client and the server. Thanks to this, there is no need to refresh the page in order to enjoy the website.

Today, Web 2.0 is everywhere, and it is a part of our everyday life. Facebook is a perfect example of a Web 2.0 site, with complete interaction between users and the storage of massive amounts of information in its database. Web applications have been popularized as webmails or Google web applications.

It's in this philosophy that Django emerged.

What is Django?

Django was born in 2003 in a press agency of Lawrence, Kansas. It is a web framework that uses Python to create websites. Its goal is to write very fast dynamic websites. In 2005, the agency decided to publish the Django source code in the BSD license. In 2008, the Django Software Foundation was created to support and advance Django. Version 1.00 of the framework was released a few months later.

Note

Django's slogan

The web framework for perfectionists with deadlines.

Django's slogan is explicit. This framework was created to accelerate the development phase of a site, but not exclusively. Indeed, this framework uses the MVC pattern, which enables us to have a coherent architecture, as we will see in the next chapter.

Until 2013, Django was only compatible with Python version 2.x, but Django 1.5 released on February 26, 2013, points towards the beginning of Python 3 compatibility.

Today, big organizations such as the Instagram mobile website, Mozilla.org, and Openstack.org are using Django.

Django – a web framework

A framework is a set of software that organizes the architecture of an application and makes a developer's job easier. A framework can be adapted to different uses. It also gives practical tools to make a programmer's job faster. Thus, some features that are regularly used on a website can be automated, such as database administration and user management.

Once a programmer handles a framework, it greatly improves their productivity and the code quality.

The MVC framework

Before the MVC framework existed, web programming mixed the database access code and the main code of the page. This returned an HTML page to the user. Even if we are storing CSS and JavaScript files in external files, server-side language codes are stored in one file that is shared between at least three languages: Python, SQL, and HTML.

The MVC pattern was created to separate logic from representation and have an internal architecture that is more tangible and real. The Model-View-Controller (MVC) represents the three application layers that the paradigm recommends:

Models: These represent data organization in a database. In simple words, we can say that each model defines a table in the database and the relations between other models. It's thanks to them that every bit of data is stored in the database.Views: These contain all the information that will be sent to the client. They make views that the final HTML document will generate. We can associate the HTML code with the views.Controllers: These contain all the actions performed by the server and are not visible to the client. The controller checks whether the user is authenticated or it can generate the HTML code from a template.

The following are the steps that are followed in an application with the MVC pattern:

The client sends a request to the server asking to display a page.The controller uses a database through models. It can create, read, update, or delete any record or apply any logic to the retrieved data.The model sends data from the database; for example, it sends a product list if we have an online shop.The controller injects data into a view to generate it.The view returns its content depending on the data given by the controller.The controller returns the HTML content to the client.

The MVC pattern enables us to get coherence for each project's worker. In a web agency where there is a web designer and there are developers, the web designer is the head of the views. Given that views contain only the HTML code, the web designer will not be disturbed by the developer's code. Developers edit their models and controllers.

Django, in particular, uses an MVT pattern. In this pattern, views are replaced by templates and controllers are replaced by views. In the rest of this book, we will be using MVT patterns. Hence, our HTML code will be templates, and our Python code will be views and models.

Why use Django?

The following is a nonexhaustive list of the advantages of using Django:

Django is published under the BSD license, which assures that web applications can be used and modified freely without any problems; it's also free.Django is fully customizable. Developers can adapt to it easily by creating modules or overridden framework methods.This modularity adds other advantages. There are a lot of Django modules that you can integrate into Django. You can get some help with other people's work because you will often find high-quality modules that you might need.Using Python in this framework allows you to have benefits from all Python libraries and assures a very good readability.Django is a framework whose main goal is perfection. It was specifically made for people who want clear code and a good architecture for their applications. It totally respects the Don't Repeat Yourself (DRY) philosophy, which means keeping the code simple without having to copy/paste the same parts in multiple places.With regards to quality, Django integrates lots of efficient ways to perform unit tests.Django is supported by a good community. This is a very important asset because it allows you to resolve issues and fix bugs very fast. Thanks to the community, we can also find code examples that show the best practices.

Django has got some disadvantages too. When a developer starts to use a framework, he /she begins with a learning phase. The duration of this phase depends on the framework and the developer. The learning phase of Django is relatively short if the developer knows Python and object-oriented programming.

Also, it can happen that a new version of the framework is published that modifies some syntax. For example, the syntax of the URLs in the templates was changed with Version 1.5 of Django. (For more details, visit https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#url.) Despite this, the documentation provides details of each Django update.

Summary

In this chapter, we studied the changes that have enabled the Web to evolve into Web 2.0. We also studied the operation of MVC that separates logic from representation. We finished the chapter with an introduction to the Django framework.

In the next chapter, we will set up our development environment with Python, PIP, and Django.

Chapter 2. Creating a Django Project

At the end of this chapter, you will have all the necessary elements to begin programming with Django. A website developed with Django is a project that contains one or more applications. Indeed, when a website becomes more important, it becomes necessary to logically separate it into several modules. These modules are then placed in the project that corresponds to the website. In this book, we will not need to create many applications, but they can be very helpful in some cases. Indeed, if one day you create an application and you want to use it in another project, you will need to copy and adapt this application to the new project.

To be able to use Django, you need to install the following software:

Python 3, to enjoy the third version innovations.setuptools is a module that simplifies the installation of the external Python module. However, it does not manage to uninstall the module.PIP extends the possibilities of setuptools by removing packages, using easier syntax, and providing other benefits.Django, which that we are going to install thanks to PIP.

These installations will be compatible with Windows, Linux, and Mac OS X.

Installing Python 3

To use all the tools that we have talked about so far, we first need to install Python 3. The following sections describe how we can install Python on different operating systems.

Installing Python 3 for Windows

To download the Python executable, visit http://www.python.org/download/ and download the Python MSI file. Please make sure that you choose the right version concerning your platform. The Python installation may need an administrator account.

For all the stages of the Python installation, you can leave all the settings at their default values. If the installation has been done properly, you should see the following dialog window open:

Installing Python 3 for Linux

To set up Python 3 on Linux, we can use the packet manager APT with the following command:

root@debian:apt-get install python3

Tip

Downloading the example code

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

We need to confirm the modifications proposed by APT.

Installing Python 3 for Mac OS

The latest version of Mac OS already has a version of Python. However, Version 2 of Python is installed, and we would like to install Version 3. To do this, visit https://www.python.org/download/ and download the right version. Then, open the file with the extension .dmp. Finally, run the file with the extension .mpkg. If you get an error such as Python cannot be opened because it is from an unidentified developer, perform the following steps:

In Finder, locate the Python install.Press the ctrl key and then click on the app's icon.Select Open from the shortcut menu.Click on Open.

Installing setuptools

PIP is a dependence of setuptools. We need to install setuptools to use PIP. The following sections describe how we can install setuptools on different operating systems.

Installing setuptools for Windows

To download the setuptools executable, you have to go to the PyPI website at https://pypi.python.org/pypi/setuptools. Then, we need to click on Downloads and select the right version. In this book, we use Version 1.1, as shown in the following screenshot:

Installing setuptools for Linux

When using APT, we do not need to install setuptools. Indeed, APT will automatically install it before installing PIP.

Installing setuptools for Mac OS

When we install PIP with the get-pip.py file, setuptools will be directly installed. Therefore, we do not need to install it for the moment.

Installing PIP

PIP is very popular among Python users, and using PIP is a Django community best practice. It handles the package installation, performs updates, and removes all the Python package extensions. Thanks to this, we can install all the required packages for Python.

If you have installed Python 3.4 or later, PIP is included with Python.

Installing PIP for Windows

To install PIP, first download it from https://pypi.python.org/pypi/pip/1.5.4.

Then, we need to install PIP from the executable, but don't forget to define the right Python installation folder, as you can see in the following screenshot:

For the next set of steps, go with the default options and complete the installation. With PIP, we will be installing all the required Python packages.

Installing PIP for Linux

To install PIP and all the components including setuptools for Linux, you have to use the get-pip.py file with the following commands:

root@debian: wget https://raw.github.com/pypa/pip/master/contrib/get-pip.pyroot@debian:python3 get-pip.py

Installing PIP for Mac OS

To install PIP on Mac OS, we must use the get-pip.py file in the following manner:

curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py sudo python3 get-pip.py

Installing Django

We will then install the framework on which we will be working. The following sections describe how we can install Django on different operating systems.

Installing Django for Windows

To install Django with PIP, you have to open a command prompt and go to the Scripts directory that you can find in the Python folder. You can install Django with the following command:

C:\Python33\Scripts\pip.exe install django=="X.X"

PIP will download and install the Django packages in the site-packages repository of Python.

Installing Django for Linux

To facilitate the PIP utilization that we have just installed, we have to look for the version installed on the system and define an alias to refer to the PIP version installed. Do not forget to execute the following commands as root:

root@debian:compgen -c | grep piproot@debian:alias pip=pip-3.2root@debian:pip install django=="1.6"

The first command looks for a usable command containing the word pip. You will certainly find a line such as pip-3.2. It's on this command that we will define an alias with the second command.

The third command installs Version 1.6 of Django.

Installing Django for Mac OS

If you want to use PIP more easily, we can create a symbolic link with the following commands:

cd /usr/local/binln -s ../../../Library/Frameworks/Python.framework/Version/3.3/bin/pip3 pip

We can then install Django using the following command:

pip install django=="1.6"

Starting your project with Django

Before you start using Django, you need to create an environment for your applications. We will create a Django project. This project will then contain our applications.

To create the project of our application, we need to run the following command using the django-admin.py file (you can find it in the Python33\Scripts folder):

django-admin.py startproject Work_manager

So as to facilitate the use of the Django commands, we can set the environmental variable of Windows. To do this, you must perform the following steps:

Right-click on My computer on the desktop.Click on Advanced System Settings.Next, click on Environmental Variable.Add or update the PATH variable:
If it does not exist, create the PATH variable and set its value as C:\Python33/ScriptsIf it exists, append ;C:\Python33\Scripts to the existing value
Now, you can use the precedent command without the need to put yourself in the Python33/Scripts folder.

Note

There are different ways to perform the previous command:

The following command will be performed in all cases:
C:\Python33\python.exe C:\Python33\Scripts\django-admin.py startproject Work_manager
The following command will be performed if we have defined C:\Python33\Scripts in the PATH variable:
C:\Python33\python.exe django-admin.py startproject Work_manager
The following command will be performed if we have defined C:\Python33\Scripts in the PATH variable and the .py extension file is defined to run with Python:
django-admin.py startproject Work_manager

This command creates a Work_manager folder in the folder from where you run the command. We will find a folder and a file in that folder:

The manage.py file will be used for actions performed on the project such as starting the development server or synchronizing the database with the models.The Work_manager folder represents an application of our project. By default, the startproject command creates a new application.

The Work_manager folder contains two very important files:

The settings.py file contains the parameters of our project. This file is common to all our applications. We use it to define the debug mode, configure the database, or define Django packages that we will use. The settings.py file allows us to do more things, but our use will be limited to what has been previously described.
The urls.py file contains all our URLs. It is with this file that we make the routing in Django. We will cover this in the next chapter.

Creating an application

We will not program our application in the Work_manager folder because we want to create our own Task_manager application.

For this, run the following command using the manage.py file created by the startproject command You must run the following command in the Work_manager folder which contains manage.py file:

Manage.py startapp TasksManager

This command creates a TasksManager folder in the folder of our project. This folder contains five files:

The __ init__.py file defines a package. Python needs it to differentiate between the standard folders and the packages.The admin.py file is not useful at this moment. It contains the models that need to be incorporated in the administration module.The models.py file contains all the models of our application. We use it a lot for the development of our application. Models allow us to create our database and store information. We will discuss this in Chapter 5, Working with Models.The tests.py file contains the unit tests of our application.The views.py file can contain views. This file will contain all the actions before sending the HTML page to the client.

Now that we know the most important files of Django, we can configure our project.

Summary

In this chapter, we have installed all the software needed to use Django. In this chapter, we learned how to create a Django project and an application. We also learned how to configure an application.

In the next chapter, we will start the Django development with an example of a web page containing the text Hello World!.

Regular expressions

Regular expressions are like a small language in itself. Despite their complex and inaccessible air, they can manipulate the strings with great flexibility. They comprise a sequence of characters to define a pattern.

We will not explore all the concepts of regular expressions in this book, because it would require several chapters and divert us from the main goal of this book. Practice your regular expressions before you write your first URLs; many sites help you train on regular expressions. Search for Online regex matcher, and you will find pages to check your regular expressions through JavaScript. You can further explore regular expressions through the book, Mastering Regular Expressions Python, Packt Publishing, written by Félix López. There is a practical tool to visualize regular expressions. This tool is called Regexper and was created by Jeff Avallone. We will use this to represent regular expressions as a diagram.

The following sections explore the patterns used, functions, and an example to help you understand regular expressions better.

The uninterpreted characters

Uninterpreted characters, such as letters and digits, in a regular expression mean that they are present in the string and must be placed in exactly the same order.

For example, the regular expression test01 will validate the test01, dktest01, and test0145g strings but won't validate test10 or tste01.

The regular expression test-reg will validate a test-regex but not test-aregex or testregex:

A visual representation of the test01 regular expression

The beginning and the end of the line

To check whether a string must be present at the beginning or the end of the line, you must use the ^ and $ characters. If ^ is present at the beginning of the string, the validation will be done at the beginning of the chain. It works in the same way for $ at the end.

The following are some examples:

The ^test regular expression will validate test and test01l but not dktest or ttest01:The regular expression test$ will validate test and 01test, but not test01:The regular expression ^test$ will only validate test:

The any character regular expression

In a regular expression, the dot (.) means "any character". So, when you validate characters that cannot be inferred, the dot is used. If you try to validate a dot in your speech, use the escape character, \.

The following are examples:

^te.t validates test or tept:^test\.me$ only validates test.me:

Character classes

To validate the characters, you can use character classes. A character class is enclosed in square brackets and contains all the allowed characters. To validate all the numbers and letters in a location, you must use [0123456789a]. For example, ^tes[t0e]$ will only validate the three chains: test, tes0, and tese.

You can also use the following predefined classes:

[0-9] is equivalent to [0123456789][a-z] matches all the letters, [abcdefghijklmnopqrstuvwxyz][A-Z] matches all uppercase letters[a-zA-Z] matches all the letters

The following are the shortcuts:

\d is equivalent to [0-9]\w is equivalent to [a-zA-Z0-9_][0-9] is equivalent to [0123456789]

Validating the number of characters

Everything that we have studied until now is the elements that define one and only one character. To validate a character one or more times, you must use braces {x, y}, where x defines the minimum number of occurrences and y is the maximum number of occurrences. If one of them is not specified, you will have an undefined value. For example, if you forget to include an element in {2,}, it means that the character must be present at least twice.

The following are some examples:

^test{2, 3}$ only validates testt and testtt:^tests{0,1}$ only validates test and tests. ^ {1} $ validates all the channels except one: the empty string

The following are the shortcuts:

* is equivalent to {0}? is equivalent to {0, 1}+ is equivalent to {1}

Regular expressions are very powerful and will be very useful even outside of programming with Django.

Creating our first URL

One of the interesting features of Django is to contain a development server. Indeed, during the development phase of the site, the developer does not need to set up a web server. However, when you put the site into production, you will need to install a real web server because it is not for use in production.

Indeed, the Django server is not secure and can hardly bear a heavy load. This does not mean that your site will be slow and full of flaws; it just means that you have to go through a real web server into production.

To use the development server, we need to use the manage.py runserver command file. We must launch the command prompt and put ourselves in the project root (use the cd command to browse folders) to execute the command:

manage.py runserver 127.0.0.1:8000

This command starts the Django development server. Let's explain the control step by step:

The runserver parameter starts the development server.127.0.0.1 is our internal IP address to the network adapter. This means that our server will listen and respond only to the computer on which it is launched. If we were in a local network and wanted to make our website available on computers other than ours, we would enter our local IP address instead of 127.0.0.1. The value 127.0.0.1 is the default value of the parameter.8000 defines the listening port of the server. This setting is useful to run multiple web servers on a single computer.

If the command is executed correctly, the window should show us the message, 0 errors found, as shown in the following screenshot:

To see the result, we must open our browser and enter the following URL: http://localhost:8000.

Django confirms that our development environment is functional by displaying the following message:

This message also means that we have no specified URL. We will add two URLs to our file:

url (r'^$', 'TasksManager.views.index.page), url (r'^index$', 'TasksManager.views.index.page')

Tip

You should consistently get to know about bugs in Django, especially on the GitHub page for Django: https://github.com/django.

In the URLs that we enter, we define the first parameter (regular expression) that will validate the URL. We will discuss the second argument in the following chapter.

Let's go back to our browser and refresh the page with the F5 key. Django will display a ViewDoesNotExist at / error.

This means that our module does not exist. You must study your errors; in this example, we had an error. With this error, we will directly fix the part that does not work.

Another problem that we regularly encounter is the 404 Page not found error. We can generate it by typing the http://localhost:8000/test404 URL in our browser. This error means that no URL has been validating the test404 string.

We must pay attention to errors because seeing and resolving them can save us a lot of time.