70,79 €
From an idea to a prototype – a complete guide for web development with the Django framework
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.
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.
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:
Seitenzahl: 788
Veröffentlichungsjahr: 2016
From an idea to a prototype – a complete guide for web development with the Django framework
A course in three modules
BIRMINGHAM - MUMBAI
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
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
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.
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.
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:
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:
Hence, it is highly recommended that you first create a separate virtual environment, as mentioned in Module 3, Chapter 2, Application Design.
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.
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.
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.
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:
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:
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!
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 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.
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.
Django Essentials
Develop simple web applications with the powerful Django framework
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 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.
The Web was born 25 years ago, thanks to growing new technologies. Two of these have been very decisive:
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.
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:
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.
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.
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.
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.
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:
The following are the steps that are followed in an application with the MVC pattern:
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.
The following is a nonexhaustive list of the advantages of using Django:
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.
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.
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:
These installations will be compatible with Windows, Linux, and Mac OS X.
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.
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:
To set up Python 3 on Linux, we can use the packet manager APT with the following command:
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.
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:
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.
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:
When using APT, we do not need to install setuptools. Indeed, APT will automatically install it before installing PIP.
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.
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.
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.
To install PIP and all the components including setuptools for Linux, you have to use the get-pip.py file with the following commands:
To install PIP on Mac OS, we must use the get-pip.py file in the following manner:
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.
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:
PIP will download and install the Django packages in the site-packages repository of Python.
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:
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.
If you want to use PIP more easily, we can create a symbolic link with the following commands:
We can then install Django using the following command:
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):
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:
There are different ways to perform the previous command:
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 Work_manager folder contains two very important files:
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:
This command creates a TasksManager folder in the folder of our project. This folder contains five files:
Now that we know the most important files of Django, we can configure our project.
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 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.
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
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:
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:
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:
The following are the shortcuts:
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:
The following are the shortcuts:
Regular expressions are very powerful and will be very useful even outside of programming with Django.
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:
This command starts the Django development server. Let's explain the control step by step:
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:
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.
