Web Development with Django Cookbook - Second Edition - Aidas Bendoraitis - E-Book

Web Development with Django Cookbook - Second Edition E-Book

Aidas Bendoraitis

0,0
43,19 €

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

Mehr erfahren.
Beschreibung

Over 70 practical recipes to help you create scalable websites using the Django 1.8 framework

About This Book

  • This is the latest book on the market that will help you take advantage of the new features added to Django 1.8
  • This book consists of recipes of varying complexities to help you create multilingual, responsive, and scalable websites with Django
  • This updated edition teaches you major Django functions and will help you improve your skills by developing models, forms, views, and templates

Who This Book Is For

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.

What You Will Learn

  • Get started with the basic configuration necessary to start any Django project
  • Build a database structure out of reusable model mixins
  • Manage forms and views and get to know some useful patterns that are used to create them
  • Create handy template filters and tags that you can reuse in every project
  • Integrate your own functionality into the Django CMS
  • Manage hierarchical structures with MPTT
  • Import data from local sources and external web services as well as exporting your data to third parties
  • Implement a multilingual search with Haystack
  • Test and deploy your project efficiently

In Detail

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.

Style and approach

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 351

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

Web Development with Django Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
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
Index

Web Development with Django Cookbook Second Edition

Web Development with Django Cookbook Second Edition

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

Credits

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

About the Author

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.

About the Reviewers

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.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free Access for Packt account holders

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.

Preface

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.

What this book covers

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.

What you need for this book

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.

Who this book is for

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.

Reader feedback

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.

Customer support

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

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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you 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

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.

Questions

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.

Chapter 1. Getting Started with Django 1.8

In this chapter, we will cover the following topics:

Working with a virtual environmentCreating a project file structureHandling project dependencies with pipMaking your code compatible with both Python 2.7 and Python 3Including external dependencies in your projectConfiguring settings for development, testing, staging, and production environmentsDefining relative paths in the settingsCreating and including local settingsSetting up STATIC_URL dynamically for Subversion usersSetting up STATIC_URL dynamically for Git usersSetting UTF-8 as the default encoding for MySQL configurationSetting the Subversion ignore propertyCreating a Git ignore fileDeleting Python-compiled filesRespecting the import order in Python filesCreating app configurationDefining overwritable app settings

Introduction

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.

Working with a virtual environment

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.

Getting ready

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:

$ sudo pip install Pillow$ sudo pip install MySQL-python$ sudo pip install virtualenv

How to do it…

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:

Go to the newly created directory and create a virtual environment that uses the shared system site packages:
$ cd ~/virtualenvs$ mkdir myproject_env$ cd myproject_env$ virtualenv --system-site-packages .New python executable in ./bin/pythonInstalling setuptools………….done.Installing pip……………done.
To use your newly created virtual environment, you need to execute the activation script in your current shell. This can be done with the following command:
$ source bin/activate

You can also use the following command one for the same (note the space between the dot and bin):

$ . bin/activate
You will see that the prompt of the command-line tool gets a prefix of the project name, as follows:
(myproject_env)$
To get out of the virtual environment, type the following command:
$ deactivate

How it works…

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:

(myproject_env)$ pip install Django==1.8

See also

The Creating a project file structure recipeThe Deploying on Apache with mod_wsgi recipe in Chapter 11, Testing and Deployment

Creating a project file structure

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.

Getting ready

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.

How to do it…

Follow these steps in order to create a file structure for your project:

With the virtual environment activated, go to the project directory and start a new Django project as follows:
(myproject_env)$ django-admin.py startproject myproject

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.

How it works…

The whole file structure for a complete project in a virtual environment will look similar to the following:

See also

The Handling project dependencies with pip recipeThe Including external dependencies in your project recipeThe Configuring settings for development, testing, staging, and production environments recipeThe Deploying on Apache with mod_wsgi recipe in Chapter 11, Testing and DeploymentThe Creating and using the Fabric deployment script recipe in Chapter 11, Testing and Deployment

Handling project dependencies with pip

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.

Getting ready

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.

How to do it…

Execute the following steps one by one to prepare pip requirements for your Django project:

Let's go to your Django project that you have under version control and create the requirements directory with these text files: base.txt for shared modules, dev.txt for development environment, test.txt for testing environment, staging.txt for staging environment, and prod.txt for production.Edit base.txt and add the Python modules that are shared in all environments, line by line, for example:
# base.txtDjango==1.8djangorestframework-e git://github.com/omab/python-social-auth.git@6b1e301c79#egg=python-social-auth
If the requirements of a specific environment are the same as in the base.txt, add the line including the base.txt in the requirements file of that environment, for example:
# prod.txt -r base.txt
If there are specific requirements for an environment, add them as shown in the following:
# dev.txt -r base.txt django-debug-toolbar selenium
Now, you can run the following command in order to install all the required dependencies for development environment (or analogous command for other environments), as follows:
(myproject_env)$ pip install -r requirements/dev.txt

How it works…

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:

(myproject_env)$ pip freeze > requirements/base.txt

There's more…

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:

(myproject_env)$ pip freeze > requirements.txt

To install the modules in a new environment simply call the following command:

(myproject_env)$ pip install -r requirements.txt

Note

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.

See also

The Working with a virtual environment recipeThe Including external dependencies in your project recipeThe Configuring settings for development, testing, staging, and production environments recipe

Including external dependencies in your project

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.

Getting ready

Start with a virtual environment with a Django project in it.

How to do it…

Execute the following steps one by one:

If you haven't done this already, create an externals directory under your Django project django-myproject directory. Then, create the libs and apps directories under it.

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.

Tip

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.

The directory structure should look something similar to the following: