43,19 €
Over 70 practical recipes to help you create scalable websites using the Django 1.8 framework
This book is for intermediate-level and professional Django users who need to build projects that are multilingual, functional on devices of different screen sizes, and that scale over a period of time. If you have created websites with Django but you want to sharpen your knowledge and learn some good approaches to different aspects of web development, you should definitely read this book.
Django is a web framework that was designed to strike a balance between rapid web development and high performance. It has the capacity to handle applications with high levels of user traffic and interaction, and can integrate with massive databases on the backend, constantly collecting and processing data in real time.
Through this book, you'll discover that collecting data from different sources and providing it to others in different formats isn't as difficult as you thought. It follows a task-based approach to guide you through all the web development processes using the Django framework. We'll start by setting up the virtual environment for a Django project and configuring it. Then you'll learn to write reusable pieces of code for your models and find out how to manage database schema changes using South migrations. After that, we'll take you through working with forms and views to enter and list data. With practical examples on using templates and JavaScript together, you will discover how to create the best user experience. In the final chapters, you'll be introduced to some programming and debugging tricks and finally, you will be shown how to test and deploy the project to a remote dedicated server.
By the end of this book, you will have a good understanding of the new features added to Django 1.8 and be an expert at web development processes.
Every chapter consists of practical examples and a mix of basic and advanced recipes that will guide you through the entire web development process, starting from project configuration and taking you right through to deployment.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 351
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2014
Second Edition: January 2016
Production reference: 1220116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-677-5
www.packtpub.com
Author
Aidas Bendoraitis
Reviewers
Patrick Chan
Jake Kronika
Jorge Armin Garcia Lopez
Commissioning Editor
Dipika Gaonkar
Acquisition Editor
Nadeem N. Bagban
Content Development Editors
Arwa Manasawala
Sumeet Sawant
Technical Editor
Bharat Patil
Copy Editor
Vibha Shukla
Project Coordinator
Shweta H Birwatkar
Proofreader
Safis Editing
Indexer
Mariammal Chettiyar
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
Aidas Bendoraitis has been professionally working with web technologies for over a decade. Over the past nine years at a Berlin-based company, studio 38 pure communication GmbH, he has developed a number of small-scale and large-scale Django projects—mostly in the cultural area—together with a creative team. At the moment, he is also working as a software architect at a London-based mobile startup, Hype.
Aidas regularly attends meetups of Django User Group Berlin, occasionally visits Django and Python conferences, and writes a weblog about Django: http://djangotricks.blogspot.com/.
I would like to thank my wife, Sofja, for her support and patience while I was writing this book, even during late evenings and weekends. I would also like to thank studio 38 pure communication GmbH and namely Reinhard Knobelspies for introducing Django to me nine years ago. Finally, I would like to thank Vilnius University in Lithuania for teaching the main programming concepts, without which I wouldn't be working in the positions I currently have.
Patrick Chan is a device and configuration management SME (subject matter expert), working in the telecommunication industry. His experience in Python has been instrumental in developing build systems that have not only increased developer productivity, but would also ensure operational reliability by automating software releases.
Jake Kronika is a passionate full-stack developer with over 20 years of experience. Jake's career grew alongside the evolution of the web development space. Starting with GeoCities and Angelfire, his skills have gradually expanded from simple HTML and copy and paste scripts to encapsulate a deep understanding of CSS. JavaScript skills that span core ECMAScript standards as well as numerous client-side libraries and powerful frameworks, such as Node.js and AngularJS; scripting languages including Python and PHP; and various databases, MySQL and PostgreSQL among them.
Jake is currently senior software engineer with CDK Global Digital Marketing wing and a PHP developer with Webkey LLC. Outside these roles, Jake also operates a sole proprietorship through which he provides services spanning the full spectrum of web administration, design, and development.
In addition to his professional career experience, Jake has acted as a reviewer for numerous other Packt titles, such as Django JavaScript Integration: AJAX and jQuery (2011), jQuery UI 1.8: The User Interface Library for jQuery (2011), jQuery Tools UI Library (2012), and Developing Responsive Web Applications with AJAX and jQuery (2014).
I would like to thank my family for their ongoing love and support.
Jorge Armin Garcia Lopez is a very passionate information security consultant from Mexico with more than seven years of experience in computer security, penetration testing, intrusion detection/prevention, malware analysis, and incident response. He is the head of GCS-CERT. He is also a security researcher at Cipher Storm Ltd and is the cofounder and CEO of the most important security conference in Mexico, called BugCON. He holds important security industry certifications such as OSCP, GCIA, and GPEN.
He loves reviewing code and books about information security and programming languages. He has worked on the books Penetration Testing with Backbox, Penetration Testing with the Bash Shell, Learning OpenStack Networking (Neutron), Django Essentials, and Getting Started with Django, all by Packt Publishing.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Django framework is relatively easy to learn and it solves many web-related questions, such as project structure, database object-relational mapping, templating, form validation, sessions, authentication, security, cookie management, internationalization, basic administration, interface to access data from scripts, and so on. 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.
Web Development with Django Cookbook - Second Edition will guide you through all the web development process with Django 1.8 framework. You will get started with the virtual environment and configuration of the project. Then, you will learn how to define the database structure with reusable components. The book will move on to the forms and views to enter and list the data. Then, you will continue with responsive templates and JavaScript to create the best user experience. After this, you will find out how to tweak administration in order to make the website editors happy. You will also learn how to integrate your own functionality in Django CMS. The next step will be to learn how to use hierarchical structures. You will find out that collecting data from different sources and providing data to others in different formats isn't as difficult as you thought. Then, you'll be introduced to some programming and debugging tricks. Finally, you will be shown how to test and deploy the project to a remote dedicated server.
In contrast to other Django books, this book will deal not only with the code of the framework itself, but also with some important third-party modules that are necessary for fully-equipped web development. Also, the book gives examples of rich user interfaces using Bootstrap frontend framework and jQuery JavaScript library.
Chapter 1, Getting Started with Django 1.8, guides you through the basic configuration that is necessary to start any Django project. It will cover topics such as the virtual environment, version control, and project settings.
Chapter 2, Database Structure, teaches how to write reusable pieces of code to use in your models. When you create a new app, the first thing to do is to define your models. Also, you will be asked how to manage the database schema changes using Django migrations.
Chapter 3, Forms and Views, shows you some patterns used to create the views and forms for your data.
Chapter 4, Templates and JavaScript, covers practical examples of using templates and JavaScript together. We will bring together templates and JavaScript as information is always presented to the user by rendered templates and in modern website, JavaScript is a must for a rich user experience.
Chapter 5, Custom Template Filters and Tags, explains how to create and use your own template filters and tags. As you will see, the default Django template system can be extended to match template developers' needs.
Chapter 6, Model Administration, guides you through extending the default administration with your own functionality as the Django framework comes with a handy pre-built model administration.
Chapter 7, Django CMS, deals with the best practices of using Django CMS, which is the most popular open source content management system made with Django, and adapting it to your project's requirements.
Chapter 8, Hierarchical Structures, shows that whenever you need to create a tree-like structure in Django, the django-mptt module comes in handy. This chapter shows you how to use it and set administration for hierarchical structures.
Chapter 9, Data Import and Export, demonstrates how to transfer data from and to different formats, as well as retrieve it from and provide it to different sources. This chapter deals with the management commands for data import and also APIs for data export.
Chapter 10, Bells and Whistles, shows some additional snippets and tricks useful in everyday web development and debugging.
Chapter 11, Testing and Deployment, teaches how to test your project and deploy it on the remote server.
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.
All other specific requirements are separately mentioned in each recipe.
If you have created websites with Django, but you want to sharpen your knowledge and learn some good approach for how to treat different aspects of web development, this book is for you. It is intended for intermediate and professional Django users who need to build projects that are multilingual, functional on devices of different screen sizes, and that scale over time.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
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.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright 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.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
In this chapter, we will cover the following topics:
In this chapter, we will see a few good practices when starting a new project with Django 1.8 on Python 2.7 or Python 3. Some of the tricks introduced here are the best ways to deal with the project layout, settings, and configurations. However, for some tricks, you might have to find some alternatives online or in other books about Django. Feel free to evaluate and choose the best bits and pieces for yourself while digging deep into the Django world.
I am assuming that you are already familiar with the basics of Django, Subversion and Git version control, MySQL and PostgreSQL databases, and command-line usage. Also, I am assuming that you are probably using a Unix-based operating system, such as Mac OS X or Linux. It makes more sense to develop with Django on Unix-based platforms as the websites will most likely be published on a Linux server, therefore, you can establish routines that work the same while developing as well as deploying. If you are locally working with Django on Windows, the routines are similar; however, they are not always the same.
It is very likely that you will develop multiple Django projects on your computer. Some modules such as Python Imaging Library (or Pillow) and MySQLdb, can be installed once and then shared for all projects. Other modules such as Django, third-party Python libraries, and Django apps, will need to be kept isolated from each other. The virtualenv tool is a utility that separates all the Python projects in their own realms. In this recipe, we will see how to use it.
To manage Python packages, you will need pip. It is included in your Python installation if you are using Python 2.7.9 or Python 3.4+. If you are using another version of Python, install pip by executing the installation instructions at http://pip.readthedocs.org/en/stable/installing/. Let's install the shared Python modules Pillow and MySQLdb, and the virtualenv utility, using the following commands:
Once you have your prerequisites installed, create a directory where all your Django projects will be stored, for example, virtualenvs under your home directory. Perform the following steps after creating the directory:
You can also use the following command one for the same (note the space between the dot and bin):
When you create a virtual environment, a few specific directories (bin, build, include, and lib) are created in order to store a copy of the Python installation and some shared Python paths are defined. When the virtual environment is activated, whatever you have installed with pip or easy_install will be put in and used by the site packages of the virtual environment, and not the global site packages of your Python installation.
To install Django 1.8 in your virtual environment, type the following command:
A consistent file structure for your projects makes you well-organized and more productive. When you have the basic workflow defined, you can get in the business logic quicker and create awesome projects.
If you haven't done this yet, create a virtualenvs directory, where you will keep all your virtual environments (read about this in the Working with a virtual environment recipe). This can be created under your home directory.
Then, create a directory for your project's environment, for example, myproject_env. Start the virtual environment in it. I would suggest adding the commands directory for local bash scripts that are related to the project, the db_backups directory for database dumps, and the project directory for your Django project. Also, install Django in your virtual environment.
Follow these steps in order to create a file structure for your project:
For clarity, we will rename the newly created directory as django-myproject. This is the directory that you will put under version control, therefore, it will have the .git, .svn, or similar directories.
In the django-myproject directory, create a README.md file to describe your project to the new developers. You can also put the pip requirements with the Django version and include other external dependencies (read about this in the Handling project dependencies with pip recipe). Also, this directory will contain your project's Python package named myproject; Django apps (I recommend having an app called utils for different functionalities that are shared throughout the project); a locale directory for your project translations if it is multilingual; a Fabric deployment script named fabfile.py, as suggested in the Creating and using the Fabric deployment script recipe in Chapter 11, Testing and Deployment; and the externals directory for external dependencies that are included in this project if you decide not to use pip requirements.In your project's Python package, myproject, create the media directory for project uploads, the site_static directory for project-specific static files, the static directory for collected static files, the tmp directory for the upload procedure, and the templates directory for project templates. Also, the myproject directory should contain your project settings, the settings.py and conf directories (read about this in the Configuring settings for development, testing, staging, and production environments recipe), as well as the urls.py URL configuration.In your site_static directory, create the site directory as a namespace for site-specific static files. Then, separate the separated static files in directories in it. For instance, scss for Sass files (optional), css for the generated minified Cascading Style Sheets, img for styling images and logos, js for JavaScript, and any third-party module combining all types of files such as the tinymce rich-text editor. Besides the site directory, the site_static directory might also contain overwritten static directories of third-party apps, for example, cms overwriting static files from Django CMS. To generate the CSS files from Sass and minify the JavaScript files, you can use the CodeKit or Prepros applications with a graphical user interface.Put your templates that are separated by the apps in your templates directory. If a template file represents a page (for example, change_item.html or item_list.html), then directly put it in the app's template directory. If the template is included in another template (for example, similar_items.html), put it in the includes subdirectory. Also, your templates directory can contain a directory called utils for globally reusable snippets, such as pagination, language chooser, and others.The whole file structure for a complete project in a virtual environment will look similar to the following:
The pip is the most convenient tool to install and manage Python packages. Besides installing the packages one by one, it is possible to define a list of packages that you want to install and pass it to the tool so that it deals with the list automatically.
You will need to have at least two different instances of your project: the development environment, where you create new features, and the public website environment that is usually called the production environment in a hosted server. Additionally, there might be development environments for other developers. Also, you may have a testing and staging environment in order to test the project locally and in a public website-like situation.
For good maintainability, you should be able to install the required Python modules for development, testing, staging, and production environments. Some of the modules will be shared and some of them will be specific. In this recipe, we will see how to organize the project dependencies and manage them with pip.
Before using this recipe, you need to have pip installed and a virtual environment activated. For more information on how to do this, read the Working with a virtual environment recipe.
Execute the following steps one by one to prepare pip requirements for your Django project:
The preceding command downloads and installs all your project dependencies from requirements/base.txt and requirements/dev.txt in your virtual environment. As you can see, you can specify a version of the module that you need for the Django framework and even directly install from a specific commit at the Git repository for the python-social-auth in our example. In practice, installing from a specific commit would rarely be useful, for instance, only when having third-party dependencies in your project with specific functionality that are not supported in the recent versions anymore.
When you have many dependencies in your project, it is good practice to stick to specific versions of the Python modules as you can then be sure that when you deploy your project or give it to a new developer, the integrity doesn't get broken and all the modules function without conflicts.
If you have already manually installed the project requirements with pip one by one, you can generate the requirements/base.txt file using the following command:
If you want to keep things simple and are sure that, for all environments, you will be using the same dependencies, you can use just one file for your requirements named requirements.txt, by definition:
To install the modules in a new environment simply call the following command:
If you need to install a Python library from other version control system or local path, you can learn more about pip from the official documentation at http://pip-python3.readthedocs.org/en/latest/reference/pip_install.html.
Sometimes, it is better to include external dependencies in your project. This ensures that whenever a developer upgrades third-party modules, all the other developers will receive the upgraded version in the next update from the version control system (Git, Subversion, or others).
Also, it is better to have external dependencies included in your project when the libraries are taken from unofficial sources, that is, somewhere other than Python Package Index (PyPI), or different version control systems.
Start with a virtual environment with a Django project in it.
Execute the following steps one by one:
The libs directory is for the Python modules that are required by your project, for example, boto, Requests, Twython, Whoosh, and so on. The apps directory is for third-party Django apps, for example, django-cms, django-haystack, django-storages, and so on.
I highly recommend that you create the README.txt files in the libs and apps directories, where you mention what each module is for, what the used version or revision is, and where it is taken from.
