Sams Teach Yourself Django In 24 Hours Mar 2008 ISBN 067232959X

  

Sams Teach Yourself Django in 24 Hours

  by Brad Dayley Publisher: Sams Pub Date: February 20, 2008

  Print ISBN-10: 0-672-32959-X Print ISBN-13: 978-0-672-32959-3 eText ISBN-10: 0-7686-8033-6 eText ISBN-13: 978-0-7686-8033-1

  Pages: 528

  

Overview

  In just 24 lessons of one hour or less, you will be able to build full-featured production websites using Django, the powerful web development framework based on Python. Designed for experienced website developers who have at least some familiarity with the Python programming language, this book uses a straightforward, step-by-step approach. Each lesson builds on the previous ones, enabling you to learn the essentials of implementing the Django framework on a website from the ground up.

  Step-by-step instructions carefully walk you through the most common Django tasks. Q&As, quizzes, and exercises at the end of each lesson help you test your knowledge. Notes and tips point out shortcuts and solutions. Learn how to…

  Install and configure the Django web development

  Cleanly separate data, logic, and view layers Implement site interfaces with build templates and views Utilize templates and views to store, access, and retrieve data Use the Django forms library Define custom tags and filters to minimize coding Secure sites with registration, authorization, logins, and permissions Manage sessions and cookies Implement middleware for request and response handling Create sitemaps to inform search engines of your content Internationalize your site Optimize performance with caching Deploy Django in multiple configurations Maintain sites with Django's administrator interface

  Introduction 1

  Part I: Creating the Website Framework Hour 1: Understanding Django 7 Hour 2: Creating Your First Website 19 Hour 3: Adding Models and Objects to Your Website 37 Hour 4: Creating the Initial Views 63 Part II: Implementing the Website Interface Hour 5: Using Data from the Database in Views 81

  Hour 7: Implementing Django Templates to Create Custom Views 117 Hour 8: Using Built-in Template Tags to Enhance Views 139 Hour 9: Using Built-in Template Filters to Enhance Views 155 Hour 10: Adding Forms to Views 185 Hour 11: Using Views to Add and Update Data in the Database 209 Hour 12: Utilizing Generic Views 231 Hour 13: Advanced View Configurations 269

  Part III: Implementing a Full-Featured Website Hour 14: Managing Site Users 295 Hour 15: Adding Website Security 313 Hour 16: Managing Sessions and Cookies 333 Hour 17: Customizing Models in the Admin Interface 347 Hour 18: Customizing the Admin Interface 365

Part IV: Implementing Advanced Website Components

Hour 19: Implementing Middleware 383 Hour 20: Internationalization and Localization 407 Hour 21: Creating Sitemaps 423 Hour 22: Implementing Multiple Websites 437 Hour 23: Configuring Caching 451 Hour 24: Deploying Django 465 Appendixes

  Appendix B: Django Form Field Objects 481 Appendix C: Formatting Dates and Times 491 Index 493

  Sams Teach Yourself Django in 24 Hours

  by Brad Dayley Publisher: Sams Pub Date: February 20, 2008

  Print ISBN-10: 0-672-32959-X Print ISBN-13: 978-0-672-32959-3 eText ISBN-10: 0-7686-8033-6 eText ISBN-13: 978-0-7686-8033-1

  Pages: 528

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

Copyright Sams Teach Yourself Django in 24 Hours

  Copyright © 2008 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

  ISBN-13: 978-0-672-32959-3

  Library of Congress Cataloging-in-Publication Data: Dayley, Brad.

  Sams teach yourself Django in 24 hours / Brad Dayley. p. cm.

  ISBN 978-0-672-32959-3 (pbk.) 1. Web site development. 2. Django (Electronic resource) 3. Python (Computer program language) I. Title. TK5105.888.D397 2008 006.7'6—dc22 2008001956 Printed in the United States of America First Printing January 2008

  Editor-in-Chief Mark Taub Development Editor Songlin Qiu

  Managing Editor Gina Kanouse Project Editor Jovana San Nicolas-Shirley Copy Editor Gayle Johnson Indexer Cheryl Lenser Proofreader Anne Goebel Technical Editor Timothy Boronczyk Publishing Coordinator Vanessa Evans Book Designer Gary Adair Compositor Nonie Ratcliff

Trademarks

  All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

  Every effort has been made to make this book as complete and accurate as possible, but no warranty or fitness is implied. The information provided is on an "as is" basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.

Bulk Sales

  Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419

  

  For sales outside of the U.S., please contact International Sales

   Dedication For D, A & F!

About the Author

  Brad Dayley is a senior software engineer in Novell's Product

  Development Group. He has 16 years of experience in designing, developing, and implementing software from the kernel level through web development. He is the author of several books on server and network management as well as programming languages. When he is not developing software or writing books, he can be found biking, hiking, and/or Jeeping somewhere in the remote regions of the western United States with his wife, DaNae, and four sons.

Acknowledgments

  My sincere gratitude goes out to the following persons, without whom this book could not have happened: My wife, who provides the inspiration and strength behind everything I do. Thank you for being everything for me. My friends, who force me to be more intelligent and creative than I necessarily would like to be. My editors, who made the book readable, technically accurate, and kept me on track. It seems that nothing gets by you. Thanks to Songlin Qiu for all your hard work in keeping me on the right track and ensuring the quality of the book is the best. Thanks to Gayle Johnson for making it appear as though I can actually write. Thanks to Tim Boronczyk for making sure the book is technically useful as well as technically accurate. Thanks to Jovana San Nicolas-Shirley and Gina Kanouse for seeing me through to the end. Last but not least, thanks to Mark Taber for getting the book off the ground and making it happen. All of you are the best.

We Want to Hear from You!

  As the reader of this book, you are our most important critic and commentator. We value your opinion, and we want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can email or write us directly to let us know what you did or didn't like about this book—as well as what we can do to make our books stronger.

  Please note that we cannot help you with technical problems

related to the topic of this book, and that we might not be able

to reply to every message.

  When you write, please be sure to include this book's title and author, as well as your name and phone number or email address.

  E-mail: Mail: Sams Publishing 800 East 96th Street

  Indianapolis, IN 46240 USA

Reader Services

  Visit our website and register this book at for convenient access to any updates, downloads, or errata that might be available for this book.

Introduction

  I have been working with the Django framework for about a year and a half, and I love it. Every so often you run into ideas that make absolute, complete sense, and Django is one of those. The folks at Django seem to be bent on making it the most elegant web framework available, and so far they are doing a great job.

  This was a tough book to write. The Django framework is simple to implement, but you can accomplish so much with it. The format of this book is Teach Yourself in 24 Hours. The idea is that after spending 24 hours with this book and a Django installation, you should have a pretty good idea of how to use Django to build a full-featured production website.

  Throughout this book, I use a fictitious website project called iFriends to illustrate the building blocks of a Django-powered website. The book has several "Try It Yourself" sections that take you through specific tasks of building the iFriends website. Actually do the "Try It Yourself" sections. They will help everything else make a lot more sense. They build on each other, so if you skip one, future "Try It Yourself" sections may not work properly.

  When you have finished the "Try It Yourself" sections, you will have a mostly functional website. You should easily have enough skills by then that you could tweak and finish the website on your own in only a few hours if you wanted to. There just wasn't enough room in the book to finish every component. I felt it was much more important to cover the topics that I did. I do have one disclaimer: There is absolutely no CSS code in my HTML template examples. I would much rather have used CSS code to format my HTML templates than the classic HTML tags (some of them deprecated) that I used. I chose not to include CSS for two important reasons. The first reason is room. bit more room, which I didn't have. The second reason is that this book is designed for Python programmers as well as HTML programmers. Using CSS for someone who is not as familiar with it could provide a distraction. This book is about learning to implement the Django framework. CSS programming techniques belong in a different book.

  When designing the content for this book, I tried to come up with the most relevant way to present the Django framework that will actually help programmers develop websites that are pertinent to real-world needs. I know that a few components and concepts have been left out. I welcome your comments and any suggestions on things that you feel need to be added to this book. If I get a chance, I will try to incorporate them into future revisions of the book. You can email any queries or suggestions to . I hope you enjoy the Django framework as much as I have and that the concepts in this book prove useful to you.

Who Should Read This Book

  This book should be read by anyone who is developing or even considering developing websites. The Django framework saves web developers a lot of time and headaches. This book is designed for website developers who have at least some familiarity with the Python programming language. Don't worry if you are not very familiar with Python. You should be able to pick up on what is going on with a few visits to .

Introduction

  I have been working with the Django framework for about a year and a half, and I love it. Every so often you run into ideas that make absolute, complete sense, and Django is one of those. The folks at Django seem to be bent on making it the most elegant web framework available, and so far they are doing a great job.

  This was a tough book to write. The Django framework is simple to implement, but you can accomplish so much with it. The format of this book is Teach Yourself in 24 Hours. The idea is that after spending 24 hours with this book and a Django installation, you should have a pretty good idea of how to use Django to build a full-featured production website.

  Throughout this book, I use a fictitious website project called iFriends to illustrate the building blocks of a Django-powered website. The book has several "Try It Yourself" sections that take you through specific tasks of building the iFriends website. Actually do the "Try It Yourself" sections. They will help everything else make a lot more sense. They build on each other, so if you skip one, future "Try It Yourself" sections may not work properly.

  When you have finished the "Try It Yourself" sections, you will have a mostly functional website. You should easily have enough skills by then that you could tweak and finish the website on your own in only a few hours if you wanted to. There just wasn't enough room in the book to finish every component. I felt it was much more important to cover the topics that I did. I do have one disclaimer: There is absolutely no CSS code in my HTML template examples. I would much rather have used CSS code to format my HTML templates than the classic HTML tags (some of them deprecated) that I used. I chose not to include CSS for two important reasons. The first reason is room. bit more room, which I didn't have. The second reason is that this book is designed for Python programmers as well as HTML programmers. Using CSS for someone who is not as familiar with it could provide a distraction. This book is about learning to implement the Django framework. CSS programming techniques belong in a different book.

  When designing the content for this book, I tried to come up with the most relevant way to present the Django framework that will actually help programmers develop websites that are pertinent to real-world needs. I know that a few components and concepts have been left out. I welcome your comments and any suggestions on things that you feel need to be added to this book. If I get a chance, I will try to incorporate them into future revisions of the book. You can email any queries or suggestions to . I hope you enjoy the Django framework as much as I have and that the concepts in this book prove useful to you.

Who Should Read This Book

  This book should be read by anyone who is developing or even considering developing websites. The Django framework saves web developers a lot of time and headaches. This book is designed for website developers who have at least some familiarity with the Python programming language. Don't worry if you are not very familiar with Python. You should be able to pick up on what is going on with a few visits to .

How This Book Is Organized

  This book is organized into four parts that help you quickly navigate the Django framework so that you will have the knowledge necessary to leverage the framework to build production websites. I tried to design the book to start slowly so that you will be able to build a good foundation for the Django framework. Then, as the hours (chapters) progress, the book delves deeper into different aspects of the Django framework.

   "Creating the Website Framework," covers the basics

  of installing, configuring, and using the Django framework to build basic websites. You are introduced to the model, template, and view concepts that Django uses to implement websites.

   "Implementing the Website Interface," covers

  building templates and views to build web pages. You will learn how to use templates and views to store, access, and retrieve data that is stored in the website's database.

  

"Implementing a Full-Featured Website," covers

  adding authentication, cookie handling, and other features necessary to implement a full production website. You will learn how to create users and groups and how to assign permissions to specific data.

  

"Implementing Advanced Website Components,"

  covers some of the advanced features of the Django framework that you will likely want to implement in production websites. You will learn how to implement middleware to enable advanced request and response handlers. You will also learn how to implement localized strings to add multiple-language capability to the website, implement caching to improve website performance, and deploy a Django website.

How to Use This Book

  The Teach Yourself in 24 Hours series has several unique elements that will help you as you are trying to learn the Django framework. Throughout the book, I use the following elements to draw attention to specific concepts:

  Did you Know?

  This element provides information about slightly off- topic tangents that may be beneficial to you but that are not necessarily directly related to the current section.

  By the Way

  This element provides information that is directly related to the current section but that does not necessarily flow with the text. It discusses what is happening in the background or points that you may not easily pick up on but that are important.

  Watch Out!

  This element notes important things that you need to know before proceeding through the book. It is important to read these sections to avoid problems with your website.

  The "Try It Yourself" sections are designed to take you through the steps of actually performing the tasks that you have been reading about. Do not skip these sections. They usually provide practice the concepts. At the end of each hour, you will find the following sections that are designed to help you solidify what you have read:

  The "Q&A" section poses questions and gives answers on concepts that are related to the hour but that fall outside what is covered in the book. The "Quiz" section provides questions and answers about the topics covered in each hour.

  The "Exercises" section lists activities that you can do to practice what you have learned during the hour. These exercises are a great way to strike out on your own a bit and get more confident with Django.

  Part I: Creating the Website Framework Creating the Initial Views

Hour 1. Understanding Django What You'll Learn in This Hour What the Django framework is, and why you should use it How Django uses models to define data

  

How Django uses Python functions to build views

How Django implements templates Where to configure Django projects How to use the utility

  manage.py

  What views are available in the admin interface How to install Django

  Designing and implementing websites can be fun and rewarding; however, it can also be stressful and demanding. Django is one of the best frameworks available to quickly develop full-featured production websites. Django is flexible and makes it easy to design a website that can be easily updated and expanded. As soon as you have learned the Django framework, you will be able to speed up design, implementation, and maintenance of your websites.

  The purpose of this hour is to introduce you to the Django framework and give you a basic understanding of the architecture. The rest of the hours in this book provide the in- depth details you need to implement a full-featured production website using Django. including models, views, and templates. We will also cover the utilities that you will use to configure and manage your Django projects. Then we will give you a brief overview of the admin interface that you can use to create and modify objects in your Django projects. Finally, we discuss how to install Django.

What Is Django?

  Django is a high-level web framework that simplifies website development. As a high-level web framework, Django abstracts much of the web development process, allowing developers to quickly implement database-backed websites using dynamic web pages.

  Did you Know? Django is pronounced "JAN-go" with the "D" silent.

  By dynamic, we mean web pages that are built on-the-fly using data from the browser request, URL, and a database. Dynamic pages solve several different problems. The biggest problem they solve is trying to maintain numerous static pages scattered all over a classic website. Django implements a Model View Controller (MVC) architecture to separate the data, logic, and view layers in website development. This has two major advantages. One is that it's easy to have some developers develop the database and others develop the web pages. Another is that code and URLs become much cleaner, easier to maintain, and more elegant.

  Part I: Creating the Website Framework Creating the Initial Views

Hour 1. Understanding Django What You'll Learn in This Hour What the Django framework is, and why you should use it How Django uses models to define data

  

How Django uses Python functions to build views

How Django implements templates Where to configure Django projects How to use the utility

  manage.py

  What views are available in the admin interface How to install Django

  Designing and implementing websites can be fun and rewarding; however, it can also be stressful and demanding. Django is one of the best frameworks available to quickly develop full-featured production websites. Django is flexible and makes it easy to design a website that can be easily updated and expanded. As soon as you have learned the Django framework, you will be able to speed up design, implementation, and maintenance of your websites.

  The purpose of this hour is to introduce you to the Django framework and give you a basic understanding of the architecture. The rest of the hours in this book provide the in- depth details you need to implement a full-featured production website using Django. including models, views, and templates. We will also cover the utilities that you will use to configure and manage your Django projects. Then we will give you a brief overview of the admin interface that you can use to create and modify objects in your Django projects. Finally, we discuss how to install Django.

What Is Django?

  Django is a high-level web framework that simplifies website development. As a high-level web framework, Django abstracts much of the web development process, allowing developers to quickly implement database-backed websites using dynamic web pages.

  Did you Know? Django is pronounced "JAN-go" with the "D" silent.

  By dynamic, we mean web pages that are built on-the-fly using data from the browser request, URL, and a database. Dynamic pages solve several different problems. The biggest problem they solve is trying to maintain numerous static pages scattered all over a classic website. Django implements a Model View Controller (MVC) architecture to separate the data, logic, and view layers in website development. This has two major advantages. One is that it's easy to have some developers develop the database and others develop the web pages. Another is that code and URLs become much cleaner, easier to maintain, and more elegant.

  Part I: Creating the Website Framework Creating the Initial Views

Hour 1. Understanding Django What You'll Learn in This Hour What the Django framework is, and why you should use it How Django uses models to define data

  

How Django uses Python functions to build views

How Django implements templates Where to configure Django projects How to use the utility

  manage.py

  What views are available in the admin interface How to install Django

  Designing and implementing websites can be fun and rewarding; however, it can also be stressful and demanding. Django is one of the best frameworks available to quickly develop full-featured production websites. Django is flexible and makes it easy to design a website that can be easily updated and expanded. As soon as you have learned the Django framework, you will be able to speed up design, implementation, and maintenance of your websites.

  The purpose of this hour is to introduce you to the Django framework and give you a basic understanding of the architecture. The rest of the hours in this book provide the in- depth details you need to implement a full-featured production website using Django. including models, views, and templates. We will also cover the utilities that you will use to configure and manage your Django projects. Then we will give you a brief overview of the admin interface that you can use to create and modify objects in your Django projects. Finally, we discuss how to install Django.

What Is Django?

  Django is a high-level web framework that simplifies website development. As a high-level web framework, Django abstracts much of the web development process, allowing developers to quickly implement database-backed websites using dynamic web pages.

  Did you Know? Django is pronounced "JAN-go" with the "D" silent.

  By dynamic, we mean web pages that are built on-the-fly using data from the browser request, URL, and a database. Dynamic pages solve several different problems. The biggest problem they solve is trying to maintain numerous static pages scattered all over a classic website. Django implements a Model View Controller (MVC) architecture to separate the data, logic, and view layers in website development. This has two major advantages. One is that it's easy to have some developers develop the database and others develop the web pages. Another is that code and URLs become much cleaner, easier to maintain, and more elegant.

Why Use Django?

  The biggest reason to use Django is that it's easy to set up a production website in no time at all. As soon as you have learned how to use Django to build websites, you will be able to implement basic websites in a matter of hours.

  Another reason to use Django is that components or even entire websites are portable and can be used in other websites. Only minimal reconfiguration is needed to port the views.

Understanding Models

  Django implements a Python class, , django.db.models.Model to define data models that will be used in a website. A data model is a set of definitions that define the attributes of objects that will be stored in the database. When you build your website, you create a subclass of the class and add

  Model members to that class to define specific data. Django's

  Field model interface provides a full-featured selection of field types that make it easy to define each model.

  The models you define in your project are synchronized to an SQL database backend as tables. Django also provides a nice database interface that lets you access data in the database

  

  "Using Data from the Database in Views."

Understanding Views

  Rendering a view from an URL request is a multistep process in Django. When a Django server receives an URL request, it parses the URL and, using a set of previously defined patterns, determines which Python code should render the view.

  The way it works is that as you design your website, you write Python functions that will build and render web pages. For each Python function, you define at least one URL pattern that will link a specific URL to that view function. The Django framework receives the URL request, handing the request to the view function and then sending the dynamically built response back to the web browser. We will discuss the URL configuration more in , "Creating the Initial Views."

Understanding Templates

  Django also provides a robust template parser that allows you to build templates that the view functions can use to build response web pages. This allows your Python developers to focus on building the data that should be displayed and allows your HTML programmers to focus on designing the web pages. We will discuss templates much more starting in "Implementing Django Templates to Create Custom Views."

Configuring the File settings.py

  Most of the website configuration that you need to implement is done in the file. When you create a new project, settings.py

  Django automatically adds the file to the project's settings.py root directory. The file contains the configuration settings.py for databases, installed applications, and numerous other configuration settings. The Django framework relies heavily on the file to define all kinds of behavior. settings.py

  You can also use the file to set your own global settings.py settings for the website. You can access this file as an object from within Python code in your projects. To access the file, import the settings object, as shown in the settings.py following example: from django.conf import settings.py if settings.MY_CUSTOM_SETTING: #perform custom work

  Watch Out!

  Do not try to modify settings in the file settings.py on-the-fly from Python code in your project. This can have unexpected (bad) results.

  Throughout this book, we will discuss several different settings that you need to make in the file. You can find settings.py more information about the options at settings.py .

Using the manage.py Utility

  Another file that is automatically installed in each project you create is the manage.py utility. The manage.py utility is actually a wrapper to an application called django-admin.py that needs to be located somewhere in the

  PYTHONPATH .

  The manage.py utility is used to perform all kinds of development, administration, and testing tasks. The best way to describe the manage.py utility is to list some of the commands you can implement: startproject creates a new Django project. A directory is created for the project that includes the initial files. startapp creates a new application in a Django project. A directory is created for the application that includes the initial files. syncdb synchronizes data from project models to the SQL database. runserver starts the development server. shell launches a Python interpreter shell that has access to the Django project, including the database. dbshell launches an SQL command-line client for the database.

  Usually the manage.py utility should be used from the root of your Django project. We will discuss using the manage.py utility for various tasks throughout this book. You can find more information about the manage.py utility at

Understanding the Django Development Server

  Django comes with a lightweight development HTTP server that you can use to test your website while you are developing it. The great thing about the development server is that it is just there. After you install Django, you don't need to spend time trying to hook it into some other web server to test your code. The development server works well for testing and uses few system resources. It should give you all the functionality you need to test your website. Start the development server using the following command at the root of your Django project: python manage.py runserver

  By the Way

  You can stop the development server by pressing Ctrl+Break or Ctrl+C.

Understanding the Admin Interface

  One of the best features of Django is that it comes with a full- featured, attractive admin interface that you can use to maintain websites. The admin interface lets you create, view, and modify data in your database models from an administrator perspective. The three main views that you deal with in the admin interface are the main or model view, the change list view, and the form view. The following sections briefly describe each of these views to give you an initial feel for the admin interface. We will discuss the admin interface more in

   .

Admin Model View

  The admin model view is the main view that is displayed when you access the admin interface. You can see the model view by typing the URL /admin/ into a browser: http://127.0.0.1:8000/admin/ The model view displays a list of the models that are currently installed in the admin interface for the project. From the model view, click the Add or Change link to the right of each model, as shown in , to access the add form or change list view.

  

Figure 1.1. The model view in the admin interface.

  [View full size image]

Admin Change List View

  The admin change list view displays a list of objects that currently exist in a specific model. You can access the change list view for a model by clicking the Change link next to the model in the model view, as shown in You can see the change list view by typing the URL /admin/application/model into a browser: http://127.0.0.1:8000/admin/auth/user From the change list view, you can filter the list of objects using items in the filter list or by typing text into the search box. You can also sort the items in the list in ascending or descending order by clicking one of the headings in the list. You can add new objects to the list and, subsequently, the database as well by clicking the Add user link in the upper right corner of the change list view, as shown in

  

Figure 1.2. The change list view in the admin interface.

  [View full size image]

Admin Form View

  There are two different admin form views: the change form and the add form. The change form view, shown in , displays the details of an object that currently exists in the database. You can access the change form by clicking one of the objects displayed in the change list, shown in . You can see the change form for a specific object by typing the URL /admin/application/model/object-id into a browser: http://127.0.0.1:8000/admin/auth/user/1/

Figure 1.3. The change form view in the admin interface.

  [View full size image]

  Any changes you make in the change form are saved to the database when you click the Save button. The add form is basically the same as the change form, except that it represents a new object that doesn't exist in the database. You can add data to the form, and then a new object is created. You can get to the add form by clicking the Add link in the model view, shown in or the Add user link in the change list view, shown in You can see the add form for a specific object by typing the URL /admin/application/model/add in a browser: http://127.0.0.1:8000/admin/auth/user/add/

Installing Django

  Django can easily be installed on a Linux, Mac, or Windows server. The only prerequisite is that Python 2.3 or higher must already be installed. You can find information about installing Python at .

  An SQL database isn't required to install Django. However, you will want to install one before you begin creating Django projects. You may need to install additional Python modules to support the database, depending on which database you choose. Django supports the MySQL, Postgre SQL, SQLite3, Oracle, and Microsoft SQL database backends. In this book, the examples will be based on the MySQL database.

  At this time, you can install Django in two different ways. You can install an official release, or you can download the development version. To download the development version, you will need to install the Subversion version control system from the following website: http://subversion.tigris.org/ The folks at the Django project are making a lot of great changes all the time, so you may want to use the development version if you want to implement the latest feature set. However, if you are developing a production website, you will want to use the released version.

  Django should typically be installed in the site-packages directory of the Python installation. For example, if Python is installed in /Python25, then Django would be installed in the following location: /Python25/Lib/site-packages/django steps of installing Django using each of these methods.

  By the Way

  Some Linux distributions now provide versions of Django integrated with their package management system. You can find a list of those third parties at the following URL:

  

  

Try It Yourself: Install the Released Version of

Django

  This section describes the steps to install the released version of Django. Follow these steps to download and install the Django tarball file: 1. Install Python 2.3 or later.

  2. Download the Django tarball from the following

  location:

  

http://www.djangoproject.com/download

  3. Use the following command to extract the tarball: tar xzvf Django-version.tar.gz

  

4. Change the directory to the Django directory created

  by extracting the tarball:

  cd Django-version

  5. Use the following command to install Django (you

  need to use the command on Linux so that sudo

  Django gets installed as the super user):

  6. Start a Python interpreter.

  

7. Use the following command to verify that Django is

  installed:

  import django django.VERSION

  

Try It Yourself: Install the Development Version of Django

  This section describes the steps to install the development version of Django. Follow these steps to download and install the Django tarball file:

  1. Install Python 2.3 or later.

  2. Install Subversion.

  3. Check out the Django trunk using the following Subversion command: svn co http://code.djangoproject.com/svn/django/trunk django_src

  

4. Either copy the django_src/django directory, or create a symbolic link to that directory

in the Python site-packages directory to place Django in the Python path.

  5. Copy django/bin/django-admin.py somewhere in the system path.

By the Way

  

You don't need to run because it does what was done in

setup.py steps 4 and 5.

  6. Start a Python interpreter.

  7. Use the following command to verify that Django is installed: import django django.VERSION

Summary

  This hour discussed the basic architecture of the Django framework, including models, views, and templates. Then we discussed configuring Django in the file and some settings.py of the project commands you can run using the manage.py utility.

  Then we briefly covered the admin interface that you can use to create and modify objects in your Django projects. We ended the hour by discussing what you need to do to get Django installed and running.

Q&A

   Does Django have to be placed in the site-packages directory?

   No. It just needs to be somewhere in the Python path. You could also

  manually add the Django directory to the Python path by editing the environment setting.

  PYTHONPATH

  

Where can I find information about backward-compatibility issues?

   Go to

  http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges

Workshop

  The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

   Which file is used to configure Django projects?

   Which utility would you use to install new applications to a

  Django project?

   Where can you go to create new objects in your website?

Quiz Answers

   The

  settings.py file.

   The

  manage.py utility.

   The Django admin interface for the website.

Exercises

  1. Install Python 2.3 or higher. Verify that you can access

  the python interpreter from a console prompt by issuing the following command: python

  2. Install a Django supported SQL database. The examples

  in this book use the MySQL database, however, Postgre or any of the others will work as well. "Django Resources," lists links that you can use to get download and installation instructions for each database.

  

3. Download Django and install it. Make certain that you can

  import the Django framework into a Python interpreter using the following command in the Python interpreter: import django

Hour 2. Creating Your First Website What You'll Learn in This Hour How to begin creating a Django project How to start and stop the built-in web server The steps to configure Django to access the database How to create and install an application The steps to apply a model to an application The steps to activate a model in Django How to configure Django to accept specific URL requests How to create a simple view for a web browser

  In , "Understanding Django," you learned some of the basics about the Django framework. This hour guides you through the steps of creating a functional website called iFriends. Although this website will be basic, it will be the basis for future hours to build on as you are guided through the various aspects of the Django framework.

Creating a Django Project

  Let's begin the process of creating a working website by creating a Django project. A Django project is a collection of settings that define a specific instance of Django. These settings include things such as database configuration, URL configuration, and other options that you will learn about as the

  

Try It Yourself: Create Your First Django Project

  Creating a Django project is relatively simple to do from the command prompt. In this section, you create a project called iFriends.

  1. From a command prompt, change to the directory where you want to store the code for the iFriends project.

  2. Create a directory called iFriends. This will be the root directory for the iFriends project.

  3. Change to the iFriends directory.

  

4. Type the following command to create the iFriends project:

python django-admin.py startproject iFriends

  Watch Out!

  Because the project will act as a Python package, avoid using a project name that conflicts with any existing built-in Python packages. The documentation for built- in Python packages can be found at

  

  By the Way

  There is no need to put your project code in a directory in the web server's document base. The Django framework will be responsible for executing the code. somewhere outside the web server's root. That way your code will be protected from being accessed directly from a web browser.

  The command first creates a directory called startproject iFriends, and then it stores the basic set of Python files that are needed to begin the project in the iFriends directory. The command creates the following files: startproject is an empty file that tells Python that the

  __init__.py website directory should be treated as a Python package. is the command-line utility that allows the manage.py administrator to start and manage the Django project. is the configuration file that controls the settings.py behavior of the Django project. is a Python file that defines the syntax and urls.py configures the behavior of the URLs that will be used to access the website. The basic purpose of these files is to set up a Python package that Django can use to define the website's structure and behavior. We will discuss these files a bit more in this hour and in subsequent hours as the website gets increasingly complex.

Hour 2. Creating Your First Website What You'll Learn in This Hour How to begin creating a Django project How to start and stop the built-in web server The steps to configure Django to access the database How to create and install an application The steps to apply a model to an application The steps to activate a model in Django How to configure Django to accept specific URL requests How to create a simple view for a web browser

  In , "Understanding Django," you learned some of the basics about the Django framework. This hour guides you through the steps of creating a functional website called iFriends. Although this website will be basic, it will be the basis for future hours to build on as you are guided through the various aspects of the Django framework.

Creating a Django Project

  Let's begin the process of creating a working website by creating a Django project. A Django project is a collection of settings that define a specific instance of Django. These settings include things such as database configuration, URL configuration, and other options that you will learn about as the

  

Try It Yourself: Create Your First Django Project

  Creating a Django project is relatively simple to do from the command prompt. In this section, you create a project called iFriends.