Part I, "Creating the Website Framework," covers the basics of installing, configuring, and using the Django framework to build basic websites.. What You'll Learn in This Hour What the D
Trang 1by 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
Table of Contents | Index
Overview
In just 24 lessons of one hour or less, you will be able to buildfull-featured production websites using Django, the powerfulweb development framework based on Python
Designed for experienced website developers who have at leastsome familiarity with the Python programming language, thisbook uses a straightforward, step-by-step approach Each
lesson builds on the previous ones, enabling you to learn theessentials of implementing the Django framework on a websitefrom the ground up
Step-by-step instructions carefully walk you through the mostcommon Django tasks
Q&As, quizzes, and exercises at the end of each lesson help youtest your knowledge
Notes and tips point out shortcuts and solutions
Learn how to…
Install and configure the Django web development
framework
Trang 2Implement site interfaces with build templates and viewsUtilize templates and views to store, access, and retrievedata
Use the Django forms library
Define custom tags and filters to minimize coding
Secure sites with registration, authorization, logins, andpermissions
Manage sessions and cookies
Implement middleware for request and response handlingCreate sitemaps to inform search engines of your contentInternationalize your site
Trang 3Hour 8: Using Built-in Template Tags to Enhance Views 139Hour 9: Using Built-in Template Filters to Enhance Views 155Hour 10: Adding Forms to Views 185
Hour 11: Using Views to Add and Update Data in the Database209
Trang 4Appendix B: Django Form Field Objects 481Appendix C: Formatting Dates and Times 491Index 493
Trang 6Adding, Modifying, and Viewing Objects in the AdminInterface
Trang 7Creating a Template
Rendering a Template as an HTTP Response
Extending Templates
Trang 9Workshop
Exercises
Hour 11 Using Views to Add and Update Data in theDatabase
Handling GET and POST Requests
Validating Data from a POST Against the ModelUpdating Data in the Database
Trang 10Understanding How to Use RequestContexts in TemplatesSummary
Trang 11Overriding Block Tags in a Custom Admin TemplateOverriding the Built-in Admin Views in the URLconf FileSummary
Trang 12Exercises
Hour 20 Internationalization and LocalizationLocalizing Strings in Python
Trang 14Form Field to Model Field MappingAppendix C Formatting Dates and TimesTry It Yourself
Index
Trang 16Warning and Disclaimer
Trang 17Bulk Sales
Sams Publishing offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales For
Trang 18Brad 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 thekernel level through web development He is the author of
several books on server and network management as well asprogramming languages When he is not developing software orwriting books, he can be found biking, hiking, and/or Jeepingsomewhere in the remote regions of the western United Stateswith his wife, DaNae, and four sons
Trang 19My sincere gratitude goes out to the following persons, withoutwhom 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 creativethan 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 onthe right track and ensuring the quality of the book is the best.Thanks to Gayle Johnson for making it appear as though I canactually write Thanks to Tim Boronczyk for making sure thebook is technically useful as well as technically accurate Thanks
to Jovana San Nicolas-Shirley and Gina Kanouse for seeing methrough to the end Last but not least, thanks to Mark Taber forgetting the book off the ground and making it happen All ofyou are the best
Trang 20As the reader of this book, you are our most important critic
and commentator We value your opinion, and we want to knowwhat we're doing right, what we could do better, what areasyou'd like to see us publish in, and any other words of wisdomyou're willing to pass our way
You can email or write us directly to let us know what you did ordidn't like about this book—as well as what we can do to makeour 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 andauthor, as well as your name and phone number or email
address
E-mail: feedback@samspublishing.com
Mail: Sams Publishing
800 East 96th StreetIndianapolis, IN 46240 USA
Trang 21Visit our website and register this book at informit.com/registerfor convenient access to any updates, downloads, or errata thatmight be available for this book
Trang 22I have been working with the Django framework for about ayear and a half, and I love it Every so often you run into ideasthat make absolute, complete sense, and Django is one of
those The folks at Django seem to be bent on making it themost 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 isthat after spending 24 hours with this book and a Django
installation, you should have a pretty good idea of how to useDjango to build a full-featured production website
Throughout this book, I use a fictitious website project callediFriends to illustrate the building blocks of a Django-poweredwebsite The book has several "Try It Yourself" sections thattake 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 maynot work properly
When you have finished the "Try It Yourself" sections, you willhave 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 Therejust 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 usedCSS code to format my HTML templates than the classic HTMLtags (some of them deprecated) that I used I chose not to
include CSS for two important reasons The first reason is room.Adding CSS files to all the examples would have taken quite a
Trang 23techniques belong in a different book
When designing the content for this book, I tried to come upwith the most relevant way to present the Django frameworkthat will actually help programmers develop websites that arepertinent to real-world needs I know that a few componentsand concepts have been left out I welcome your comments andany suggestions on things that you feel need to be added to thisbook If I get a chance, I will try to incorporate them into futurerevisions of the book You can email any queries or suggestions
to dayleybooks@yahoo.com
I hope you enjoy the Django framework as much as I have andthat 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 evenconsidering developing websites The Django framework savesweb 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 topick up on what is going on with a few visits to
www.python.org
Trang 24I have been working with the Django framework for about ayear and a half, and I love it Every so often you run into ideasthat make absolute, complete sense, and Django is one of
those The folks at Django seem to be bent on making it themost 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 isthat after spending 24 hours with this book and a Django
installation, you should have a pretty good idea of how to useDjango to build a full-featured production website
Throughout this book, I use a fictitious website project callediFriends to illustrate the building blocks of a Django-poweredwebsite The book has several "Try It Yourself" sections thattake 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 maynot work properly
When you have finished the "Try It Yourself" sections, you willhave 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 Therejust 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 usedCSS code to format my HTML templates than the classic HTMLtags (some of them deprecated) that I used I chose not to
include CSS for two important reasons The first reason is room.Adding CSS files to all the examples would have taken quite a
Trang 25techniques belong in a different book
When designing the content for this book, I tried to come upwith the most relevant way to present the Django frameworkthat will actually help programmers develop websites that arepertinent to real-world needs I know that a few componentsand concepts have been left out I welcome your comments andany suggestions on things that you feel need to be added to thisbook If I get a chance, I will try to incorporate them into futurerevisions of the book You can email any queries or suggestions
to dayleybooks@yahoo.com
I hope you enjoy the Django framework as much as I have andthat 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 evenconsidering developing websites The Django framework savesweb 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 topick up on what is going on with a few visits to
www.python.org
Trang 26Part I, "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 implementwebsites
Part II, "Implementing the Website Interface," covers
building templates and views to build web pages You willlearn how to use templates and views to store, access, andretrieve data that is stored in the website's database
Part III, "Implementing a Full-Featured Website," coversadding authentication, cookie handling, and other featuresnecessary to implement a full production website You willlearn how to create users and groups and how to assignpermissions to specific data
Part IV, "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 localizedstrings to add multiple-language capability to the website,implement caching to improve website performance, anddeploy a Django website
Trang 27The 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 followingelements to draw attention to specific concepts:
The "Try It Yourself" sections are designed to take you throughthe steps of actually performing the tasks that you have beenreading about Do not skip these sections They usually provideadditional information about the topic and are a great chance to
Trang 28At the end of each hour, you will find the following sections thatare designed to help you solidify what you have read:
The "Q&A" section poses questions and gives answers onconcepts that are related to the hour but that fall outsidewhat is covered in the book
The "Quiz" section provides questions and answers aboutthe topics covered in each hour
The "Exercises" section lists activities that you can do topractice what you have learned during the hour These
exercises are a great way to strike out on your own a bitand get more confident with Django
Trang 30What You'll Learn in This Hour
What the Django framework is, and why you should use it
develop full-featured production websites Django is flexible andmakes it easy to design a website that can be easily updatedand expanded As soon as you have learned the Django
architecture The rest of the hours in this book provide the in-This hour is a basic overview of the Django framework,
Trang 31What Is Django?
Django is a high-level web framework that simplifies websitedevelopment As a high-level web framework, Django abstractsmuch of the web development process, allowing developers toquickly implement database-backed websites using dynamicweb 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 usingdata from the browser request, URL, and a database Dynamicpages solve several different problems The biggest problemthey solve is trying to maintain numerous static pages scatteredall 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'seasy to have some developers develop the database and othersdevelop the web pages Another is that code and URLs becomemuch cleaner, easier to maintain, and more elegant
Trang 33What You'll Learn in This Hour
What the Django framework is, and why you should use it
develop full-featured production websites Django is flexible andmakes it easy to design a website that can be easily updatedand expanded As soon as you have learned the Django
architecture The rest of the hours in this book provide the in-This hour is a basic overview of the Django framework,
Trang 34What Is Django?
Django is a high-level web framework that simplifies websitedevelopment As a high-level web framework, Django abstractsmuch of the web development process, allowing developers toquickly implement database-backed websites using dynamicweb 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 usingdata from the browser request, URL, and a database Dynamicpages solve several different problems The biggest problemthey solve is trying to maintain numerous static pages scatteredall 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'seasy to have some developers develop the database and othersdevelop the web pages Another is that code and URLs becomemuch cleaner, easier to maintain, and more elegant
Trang 36What You'll Learn in This Hour
What the Django framework is, and why you should use it
develop full-featured production websites Django is flexible andmakes it easy to design a website that can be easily updatedand expanded As soon as you have learned the Django
architecture The rest of the hours in this book provide the in-This hour is a basic overview of the Django framework,
Trang 37What Is Django?
Django is a high-level web framework that simplifies websitedevelopment As a high-level web framework, Django abstractsmuch of the web development process, allowing developers toquickly implement database-backed websites using dynamicweb 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 usingdata from the browser request, URL, and a database Dynamicpages solve several different problems The biggest problemthey solve is trying to maintain numerous static pages scatteredall 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'seasy to have some developers develop the database and othersdevelop the web pages Another is that code and URLs becomemuch cleaner, easier to maintain, and more elegant
Trang 38The biggest reason to use Django is that it's easy to set up aproduction website in no time at all As soon as you have
learned how to use Django to build websites, you will be able toimplement basic websites in a matter of hours
Another reason to use Django is that components or even entirewebsites are portable and can be used in other websites Onlyminimal reconfiguration is needed to port the views
Trang 39Django implements a Python class, django.db.models.Model,
to define data models that will be used in a website A datamodel is a set of definitions that define the attributes of objectsthat will be stored in the database When you build your
website, you create a subclass of the Model class and add
Field members to that class to define specific data Django'smodel interface provides a full-featured selection of field typesthat make it easy to define each model
The models you define in your project are synchronized to anSQL database backend as tables Django also provides a nicedatabase interface that lets you access data in the databasefrom views and templates We will discuss models more in Hour
3, "Adding Models and Objects to Your Website," and Hour 5,
"Using Data from the Database in Views."
Trang 40Rendering a view from an URL request is a multistep process inDjango 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 writePython functions that will build and render web pages For eachPython function, you define at least one URL pattern that willlink a specific URL to that view function The Django frameworkreceives 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 Hour 4, "Creating the Initial Views."