SlideShare a Scribd company logo
Django Javascript Integration Ajax And Jquery
1st Edition Jonathan Hayward download
https://ebookbell.com/product/django-javascript-integration-ajax-
and-jquery-1st-edition-jonathan-hayward-49052714
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Django Javascript Integration Ajax And Jquery Jonathan Hayward
https://ebookbell.com/product/django-javascript-integration-ajax-and-
jquery-jonathan-hayward-4100096
Decoupled Django Understand And Build Decoupled Django Architectures
For Javascript Frontends 1st Edition Valentino Gagliardi
https://ebookbell.com/product/decoupled-django-understand-and-build-
decoupled-django-architectures-for-javascript-frontends-1st-edition-
valentino-gagliardi-33356238
Decoupled Django Understand And Build Decoupled Django Architectures
For Javascript Frontends Valentino Gagliardi
https://ebookbell.com/product/decoupled-django-understand-and-build-
decoupled-django-architectures-for-javascript-frontends-valentino-
gagliardi-47965604
Decoupled Django Understand And Build Decoupled Django Architectures
For Javascript Frontends Valentino Gagliardi
https://ebookbell.com/product/decoupled-django-understand-and-build-
decoupled-django-architectures-for-javascript-frontends-valentino-
gagliardi-47965602
Django 4 By Example Build Powerful And Reliable Python Web
Applications From Scratch 4th Antonio Mel
https://ebookbell.com/product/django-4-by-example-build-powerful-and-
reliable-python-web-applications-from-scratch-4th-antonio-mel-46085550
Django Standalone Apps Learn To Develop Reusable Django Libraries 1st
Edition Ben Lopatin
https://ebookbell.com/product/django-standalone-apps-learn-to-develop-
reusable-django-libraries-1st-edition-ben-lopatin-50195676
Django The Easy Way A Stepbystep Guide On Building Django Websites 2nd
Edition Samuli Natri
https://ebookbell.com/product/django-the-easy-way-a-stepbystep-guide-
on-building-django-websites-2nd-edition-samuli-natri-50200506
Django 10 Template Development Scott Newman
https://ebookbell.com/product/django-10-template-development-scott-
newman-50478114
Django In Action Meap V01 Chapters 1 To 5 Of 20 Christopher Trudeau
https://ebookbell.com/product/django-in-action-
meap-v01-chapters-1-to-5-of-20-christopher-trudeau-50864070
Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward
Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward
Django JavaScript Integration:
AJAX and jQuery
Develop AJAX applications using Django and jQuery
Jonathan Hayward
BIRMINGHAM - MUMBAI
Django JavaScript Integration: AJAX and jQuery
Copyright © 2010 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: January 2011
Production Reference: 1291210
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849510-34-9
www.packtpub.com
Cover Image by Vinayak Chittar (vinayak.chittar@gmail.com)
Credits
Author
Jonathan Hayward
Reviewers
Jake Kronika
Michael Szul
Acquisition Editor
Steven Wilding
Development Editor
Maitreya Bhakal
Technical Editors
Vanjeet D'souza
Conrad Sardinha
Indexers
Hemangini Bari
Monica Ajmera Mehta
Editorial Team Leader
Akshara Aware
Project Team Leader
Ashwin Shetty
Project Coordinator
Joel Goveya
Proofreader
Sandra Hopper
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Foreword
In this book, we will be exploring Django JavaScript integration and build an Ajax
application using jQuery. We will build a Web 2.0 intranet employee directory, and
we will aim for a solution that is Pythonic in more ways than one.
Web development that is more "Pythonic" than just Python
This book is intended to be a book about how to do web development in the spirit
of Python++.
The term "Python++" as we use it here is not the usual "Python is great," even if that
may also be our opinion, but a more direct analogy to C++. When the effort was
made to improve the C language, the basic kind of improvement attempted was to
expand and broaden the core language. It is no accident that Stroustrup's The C++
Programming Language is far longer than Kernigan and Ritchie's The C Programming
Language. The latter is a small book describing a small core language, while the
former is a large book made large by the large core language it describes. The analogy
intended by Python++ is somewhat loose here, and specifically does not include a
large, or even a small, expansion of the core language. It is possible to tinker with
the core language—easy_extend lets you extend Python to include a do-while loop
(where the test condition is first evaluated at the end, not the beginning)—or add
primitive syntax so you can do things like if remote_ip in 10.0.0.0:, but this
is almost beside the point.
The real possibilities for expanding Python do not need to radically expand the core
language, or change the core language at all. Django (http://www.djangoproject.
com/) is not a general purpose enhancement to Python: if you are automating system
administration tasks, for instance, you very probably have no reason to use Django.
But for a limited problem domain, namely certain kinds of web development, Django
is more Pythonic than Python. Python's cgi module is good for some kinds of small
and simple tasks, but if you are going to make a serious, large-scale web application
with many standard functions, using Python core language + Python standard library +
Django is a fundamentally more Pythonic approach than just Python core language +
Python standard library alone.
On StackOverflow, someone asked the question, "Have you considered using Django
and found good reasons not to?" There were various answers, but the answer with
the most "up" votes by far said, "I am an honest guy, and the client wanted to charge
by the hour. There was no way Django was going to make me enough money."
Django itself is not the limit to Python++. Pinax (http://pinaxproject.com/) is
built on top of Django and offers a "more Django than Django" platform to build a
social network. Satchmo (http://satchmoproject.com/) is also "more Django than
Django" for another narrower focus: e-commerce webshops. And there are other
platforms built on Django; it is time well spent to search the Python Package Index
(http://pypi.python.org/pypi) for Django to see what is already available. In this
text we will often use "Django" as a shorthand for either basic Django or any of the
many good tools built on top of Django.
Depending on what you are trying to do, it may be that the bulk of the Python work
in Django is resolved surprisingly quickly: you can build and brand a Pinax social
network by doing little more than overriding the CSS and adding images. This book
will address the Python side and try to give a solid basis for programming Python
for Django, working with the templates, and so on, but that problem can often be
solved so cleanly that most of the work that remains is styling and Ajax.
Django and its templating engine
Before further exploring technical details, it would be worth taking a look at the
opinions and philosophy behind the Django templating language, because an
understandable approach of, "������
Oh, it's a general purpose programming language
very slightly adapted for templating,�������������������������������������������
" is a recipe for needless frustration and
pain. The Django developers themselves acknowledge that their opinions in the
templating language are one just opinion in an area where different people have
different opinions, and you are welcome to disagree with them if you want. If you
don't like the templating system that Django comes with, Django is designed to let
you use another. But it is worth understanding what exactly the philosophy behind
the templating language is; even if this is not the only philosophy one could use, it is
carefully thought out.
The Django templating language is intended to foster the separation of presentation
and logic. In its design decisions, both large and small, the Django's templating engine
is optimized primarily for designers to use for designing, rather than programmers
to use for programming, and its limitations are almost as carefully chosen as the
features it provides. Unlike ASP, JSP, and PHP, it is not a programming language
interspersed with HTML. It provides enough power for presentation, is intended not
to provide enough power to do serious programming work where it doesn't belong
(in the Django opinion), and is simple enough that some non-programmers can pick
it up in a day. For a programmer, the difficulty of learning the templating basics is
comparable to the difficulty of simple HTML or SQL: it is simple, and a good bit
easier to learn than wrapping your arms around a regular programming language.
It is likely that there are a number of Django programmers out there who started by
asking, "Why doesn't the templating language just let you mix Python and HTML?"
and after playing with it, found themselves saying, "This isn't what I would have
come up with myself, but I really, really like it."
Additional benefits include it being fast (most of the work is done by a single regular
expression call, and the founders talk about disabling caching because it couldn't
keep up with the template rendering engine's speed), secure (it is designed so that it
can be used by untrusted designers without allowing a malicious designer to execute
arbitrary code), and versatile enough to generate whatever text format you want:
plain text, HTML, XML, XHTML, JSON, JavaScript, CSV, ReStructuredText, and so
on. We will be using it to generate web pages and JSON, but Django's templating
language is a general-purpose text templating solution.
What we will do in this book—building a Web 2.0 intranet
employee photo directory
Many books will teach you a new technology by walking through a sample
project. This book is no different, but the sample project is not a toy: it is a walk
through making a real, live Web 2.0 intranet employee photo directory that you can
customize to your organization's needs. This is something that is both useful, and
will give us a tour of the potential for developing Ajax applications using Django on
the server side and jQuery on the client side.
- Jonathan Hayward
About the Author
Jonathan Hayward as a child ranked 7th in a nationwide math contest, and
later programmed a video game on his calculator. He holds master's degrees in
bridging mathematics and computer science (UIUC), and philosophy and theology
(Cambridge). Jonathan has lived in the U.S., Malaysia, France, and England, and
has studied well over a dozen dialects and languages. He wears the hats of author,
philosopher, theologian, artist, poet, wayfarer, philologist, inventor, and a skilled
web developer who holds a deep interest in the human side of computing. He has a
website showcasing his works at http://JonathansCorner.com and can be reached
via e-mail at jonathan.hayward@pobox.com.
I would like to thank my parents, John and Linda, who love learning
and taught me faith, my brothers, Matthew, Kirk and Joe, my parish,
St. Innocent of Moscow, for a wealth of support. I would also like
to thank the editorial team at Packt: Steven Wilding, who helped
me come up with the book idea in the first place, Ved Prakash Jha,
who helped see it to completion, and Joel Goyeva, who helped
me with innumerable logistics along the way. And, of course, the
reviewers Jake Kronika and Michael Szul, who offered an invaluable
sharpening. The Django list, django-users@googlegroups.com, is
worth its weight in gold. I would like to thank Daniel Roseman, Alex
Robbins, Dan Harris, Karen Tracey, Oleg Lokalma, Mark Linsey, Jeff
Green, Elijah Rutschman, Brian Neal, Euan Goddard, Sævar Öfjörð,
"Ringemup", Ben Atkin, Tom Evans, Sam Lai, and Preston Holmes.
Authors have to leave somebody out who deserves to be mentioned;
that's just part of the territory. But I would like to thank one person
in particular: the reader. You're really the reason the book is here,
and you've chosen to invest some money in a book and some time in
fascinating technologies and let me help you along the way. Thank
you so much.
About the Reviewers
Jake Kronika, a web designer and developer with over fifteen years of experience,
brings to this book a strong background in frontend development with JavaScript
and AJAX, as well as exposure to the Django framework.
Having earned a Bachelors of Science degree in Computer Science from Illinois
Wesleyan University in 2005, with a minor in Business Administration, Jake went
on to become Senior User Interface (UI) Specialist for Imaginary Landscape, LLC, a
small web development firm in Ravenswood, on the north side of Chicago. In this
role, the foundations of his strengths in Cascading Style Sheets (CSS) and JavaScript
(JS) were built, as well as extensive use of Python and the Django Framework.
From there, Jake went on to work for the Sun-Times News Group, owner of the
Chicago Sun-Times and numerous suburban newspapers in Chicagoland. It was in
this role that he was initially exposed and rapidly became an expert with the jQuery
framework for JS.
Following an intermediate position as Technology Consultant with Objective
Arts, Inc, Jake has worked as UI Prototyper for JP Morgan Chase since February
2010. Since 1999, he has also operated Gridline Design & Development, a sole
proprietorship for web design, development, and administration.
I would like to thank my wife, Veronica, for her ongoing support.
She and my twin children Mykaela and Kaden provide all the joy I
could want in this world.
Michael Szul has designed and developed software applications for Fortune
500 companies, including AIG and Praxair, since 1998. Later, he served as a senior
software engineer for the technology division of Performance Media Group,
contributing to their fast growth and success, including placement on the Inc. 5000.
Szul's expertise in social software development led to a lateral move within the
company to become the director of development for their travel social network. He
even built successful social software for companies such as Apple Vacations and
Conde Naste's Gourmet Magazine.
As a partner at Barbella Digital, Inc., he currently designs and develops enterprise-
level workflow systems and mobile applications for educational institutions.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related
to your book.
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 service@packtpub.com 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.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can access, read and search across Packt's entire library
of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via 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 nine entirely free books. Simply use your login credentials
for immediate access.
•
•
•
Table of Contents
Preface 1
Chapter 1: jQuery and Ajax Integration in Django 7
Ajax and the XMLHttpRequest object 8
Human speech: An overlaid function 8
Ajax: Another overlaid function 8
The technologies Ajax is overlaid on 9
JavaScript 9
XMLHttpRequest 14
Methods 14
Properties 15
HTML/XHTML 17
XML 18
JSON 18
CSS 19
The DOM 19
iframes and other Ajax variations 20
JavaScript/Ajax Libraries 21
Server-side technologies 21
A look at Django 21
Django templating kickstart 22
A more complete glimpse at Django templating 23
Setting JavaScript and other static content in place 32
Summary 33
Chapter 2: jQuery—the Most Common JavaScript Framework 35
jQuery and basic Ajax 36
jQuery Ajax facilities 39
$.ajax() 39
context 40
data 42
Table of Contents
[ ii ]
dataFilter 43
dataType 43
error(XMLHttpRequest, textStatus, errorThrown) 44
success(data, textStatus, XMLHttpRequest) 44
type 44
url 44
$.aj0axSetup() 45
Sample invocation 45
$.get() and $.post() 45
.load() 46
jQuery as a virtual higher-level language 48
The selectors 48
A closure-based example to measure clock skew 52
Case study: A more in-depth application 56
Chapter 3: Validating Form Input on the Server Side 56
Chapter 4: Server-side Database Search with Ajax 56
Chapter 5: Signing Up and Logging into a Website Using Ajax 57
Chapter 6: jQuery In-place Editing Using Ajax 57
Chapter 7: Using jQuery UI Autocomplete in Django Templates 57
Chapter 8: Django ModelForm: a CSS Makeover 57
Chapter 9: Database and Search Handling 57
Chapter 10: Tinkering Around: Bugfixes, Friendlier Password Input,
and a Directory That Tells Local Time 58
Chapter 11: Usability for Hackers 58
Appendix: Debugging Hard JavaScript Bugs 58
Summary 58
Chapter 3: Validating Form Input on the Server Side 61
The standard lecture: low-level validation 62
Matching regular expressions 62
You cannot guarantee absolutely valid data 63
Validating can detect (some) malicious input 63
The Django way of validation 64
Django gives you some things for free 64
The steps in Django's validation 65
A more sensible and cruelty-free approach to validation 66
Things get murkier 67
The zero-one-infinity rule: a cardinal rule of thumb in usability 68
An improvement on Django's advertised approach 68
A validation example: GPS coordinates 70
Avoiding error messages that point fingers and say, "You're wrong!" 71
Table of Contents
[ iii ]
Validation as demanding that assumptions be met 72
Old-school: conform to our U.S.-based assumptions! 72
Adding the wrong kind of band-aid 74
Making assumptions and demanding that users conform 76
At least names are simple, right? 76
Even in ASCII, things keep getting murkier 77
Better validation may be less validation 78
Caveat: English is something of a lingua franca 79
We don't have to negotiate with pistols 80
Doing our best to solve the wrong problem: a story 81
It really does apply to validation 82
Facebook and LinkedIn know something better 83
Summary 83
Chapter 4: Server-side Database Search with Ajax 85
Searching on the client side and server side 86
Handling databases through Django models 86
Models for an intranet employee photo directory 87
Searching our database 95
A tour of Django persistence facilities 100
Summary 103
Chapter 5: Signing Up and Logging into a Website Using Ajax 105
admin.py: administrative functions called once 107
functions.py: project-specific functions, including our
@ajax_login_required decorator 107
views.py: functions that render web pages 108
style.css: basic styling for usability 113
search.html: a template for client-side Ajax 114
The Django admin interface 122
Summary 124
Chapter 6: jQuery In-place Editing Using Ajax 125
Including a plugin 127
How to make pages more responsive 127
A template handling the client-side requirements 128
The bulk of the profile 132
Whitespace and delivery 133
Page-specific JavaScript 136
Support on the server side 137
Summary 139
Table of Contents
[ iv ]
Chapter 7: Using jQuery UI Autocomplete in Django Templates 141
Adding autocomplete: first attempt 142
Progressive enhancement, a best practice 142
A real-world workaround 146
"Interest-based negotiation": a power tool for problem solving
when plan A doesn't work 146
A first workaround 148
Boilerplate code from jQuery UI documentation 154
Turning on Ajax behavior (or trying to) 156
Code on the server side 156
Refining our solution further 159
Summary 163
Chapter 8: Django ModelForm: a CSS Makeover 165
"Hello, world!" in ModelForm 165
Expanding and customizing the example 168
Customizing ModelForm pages' appearance 170
Going under ModelForm's hood 182
An excellent "stupid" question: where's the e-mail slot? 184
Summary 187
Chapter 9: Database and Search Handling 189
Moving forward to an AHAH solution 189
Django templates for simple AHAH 192
Templating for a list of search results 192
Template for an individual profile 195
Views on the server side 202
Telling if the user is logged in 202
A view to support deletion 202
The AHAH view to load profiles 203
Helper functions for the AHAH view for searching 204
An updated model 206
An AHAH server-side search function 207
Handling the client-side: A template for the main page 209
CSS for styling the directory 232
Our updated urlpatterns 241
Summary 241
Chapter 10: Tinkering Around: Bugfixes, Friendlier
Password Input, and a Directory That Tells Local Time 243
Minor tweaks and bugfixes 243
Setting a default name of "(Insert name here)" 244
Eliminating Borg behavior 244
Table of Contents
[  ]
Confusing jQuery's load() with html() 245
Preventing display of deleted instances 246
Adding a favicon.ico 249
Handling password input in a slightly different way 250
A directory that includes local timekeeping 252
Summary 260
Chapter 11: Usability for Hackers 261
Usability begins with anthropology… and Django hackers
have a good start on anthropology 262
Anthropological usability techniques 263
An introductory example: card sorting 263
Focus groups: cargo cult research for usability 265
Anthropological observation: the bedrock of usability 265
More than one way to see the same situation 266
Applying this foundation to usability 268
It's just like (hard) debugging 271
Lessons from other areas 272
Live cross-cultural encounters 272
History 273
Old books and literature 274
The last other area: whatever you have 277
Understanding the user 278
A lesson from optimization 278
What's wrong with scratching an itch, or you are not your user 279
Worst practices from the jargon file 279
Python and usability 280
It's not all about the computer! 280
What to do in the concrete 282
Further reading 283
Summary 284
Appendix: Debugging Hard JavaScript Bugs 285
Just fiddling with Firebug is considered harmful 285
Cargo cult debugging at your fingertips 285
The scientific method of debugging 286
Exhausting yourself by barking up the wrong tree 287
The humble debugger 289
The value of taking a break 289
Two major benefits to asking for help 290
Table of Contents
[ vi ]
Firebug and Chrome developer tools 290
The basics across browsers 290
Zeroing in on Chrome 293
Summary 298
Index 299
Preface
You want to create an AJAX application. Why would you use Django? Why would
you use jQuery? Why would you use both together? Enter Django JavaScript
Integration: AJAX and jQuery—your comprehensive answer to all these questions
and the only extensive, practical, and hands-on guide to developing any AJAX
application with Django and jQuery.
Gone are the days when you used to lament over the lack of official documentation
on AJAX with Django. This book will teach you exactly why Django is called The
web framework for perfectionists with deadlines, how jQuery—the write less do
more JavaScript library—is practically a virtual higher-level language, and why
they both deserve to be integrated with AJAX.
This hands-on-guide shows you how to put Django and jQuery together in the
process of creating an AJAX application. In this book, they are brought together
in a real-world scenario, with attention to usability, to build and develop an
AJAX application.
The first two chapters provide a short and necessary introduction to the world of
Django, jQuery, and AJAX; the remaining chapters are based on a case study that
will make you realize the immense potential and benefits of integrating Django and
jQuery with your AJAX application.
By the time you are done with this book, you'll be developing your AJAX
applications with Django and jQuery in less time than you can say integrate.
You will cover the basics of AJAX; use jQuery, the most common JavaScript library,
on the client side, and learn form validation with an eye towards usability,
build things with Django on the server side, handle login and authentication
via Django-based AJAX, and then dip into the rich jQuery plugin ecosystem
to build in-place editing into your pages.
Preface
[  ]
You will add auto-complete functionality courtesy of jQuery UI, easily build forms
with Django ModelForm, and then look at a client-side search implementation that
can look things up without network access after initial download. You will learn to
implement a simple, expandable undo system, and offer more full-blooded account
management, tinker, fix some bugs, offer a more usable way to handle password
input, add local time support for people who are not in your time zone, look at
usability, and finally take a look at debugging.
After working through this book, you will have both an AJAX application: a Web 2.0
employee intranet photo directory, and with it a deep understanding that you can
use to customize, extend, and further develop it in your organization.
What this book covers
This book covers Django JavaScript integration and building an Ajax application
with Django on the server side and jQuery on the client side. It provides first an
overview, then a first Ajax application, and introduces jQuery; discusses form
validation, server-side database search; Ajax login facilities; jQuery in-place
editing and autocomplete, Django Modelform, and how to give auto-generated
forms a transformational CSS makeover. It also discusses client-side functionality,
customization, and further development with tinkering and added features,
before a grand finale exploring usability, and an appendix on debugging hard
JavaScript bugs.
Chapter 1, jQuery and Ajax Integration in Django lays a solid foundation and introduces
you to the working pieces of Django Ajax to be explored in the
rest of the book.
Chapter 2, jQuery—the Most Common JavaScript Framework explores the higher-level
way of doing things in jQuery. You will learn how jQuery is not Python and does
not look like Python, but how there is something Pythonic in spirit about how
it works.
Chapter 3, Validating Form Input on the Server Side will teach you how to send
an Ajax request to the server via jQuery, and validate it on the server side based
on the principle that all input is guilty until proven innocent of being malicious,
malformed, incomplete, or otherwise invalid.
Chapter 4, Server-side Database Search with Ajax looks both at the merits of
handling searching and other backend functions with the full power of a backend
environment, and explores why, on the client side, you should work hard to be as
lazy as possible in doing network-related work.
Preface
[  ]
Chapter 5, Signing-up and Logging into a Website Using Ajax introduces Django
authentication facilities and account management and includes both server-side
and client-side code.
Chapter 6, jQuery In-place Editing Using Ajax goes from a basic foundation to a
continuing practical application. It will show a way to use jQuery to make an
in-place replacement of a table that allows in-place editing, which communicates
with the server in the background, adding persistence to changes.
Chapter 7, Using jQuery UI Autocomplete in Django Templates tells you what you need
on the client side and server side to get autocomplete working with jQuery UI. It also
includes creative problem solving when something goes wrong. This chapter will
tell you why it is not uncommon for programmers to write plugins their first day
doing jQuery.
Chapter 8, Django ModelForm: a CSS Makeover explores Django ModelForm and how
to use it.
Chapter 9, Database and Search Handling covers all the bases for a simple, AHAH
solution. In addition to showing lazy best practices, it also showcases a JavaScript
in-memory database, with an application designed, at the developer's preference, to
either always perform lazy handling of search and other requests, or start loading an
in-memory database and falling back to lazy handling until the in-memory database
is available.
Chapter 10, Tinkering Around: Bugfixes, Friendlier Password Input, and a Directory That
Tells Local Time covers some tinkering and tweaks, and bugfixes along the way
Chapter 11, Usability for Hackers steps back from your application and takes a look at
usability and the bedrock competencies hackers can leverage to do usability.
Appendix, Debugging Hard JavaScript Bugs looks at the state of mind that is needed to
debug difficult bugs.
What you need for this book
This book assumes a broad technical maturity and an ability to learn and integrate
different skills. It helps to be a Pythonista with the usual strengths that come with
Python, and knowledge of the Web. A basic understanding of, or the ability to learn,
Django and JavaScript will be helpful.
If you're a good generalist programmer who wants to learn Django JavaScript
integration, this book is for you.
Preface
[  ]
Who this book is for
This book is for people looking to integrate AJAX / JavaScript functionality into their
web applications. It is for Django users who are looking to easily integrate AJAX
features into their applications. Conversely, it will also be a priceless companion for
users familiar with Django and jQuery who are looking to integrate them in their
AJAX applications. A working knowledge of Django and basic familiarity with AJAX
and jQuery are assumed.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: You can override the empty string by
setting TEMPLATE_STRING_IF_INVALID in your settings.py file.
A block of code is set as follows:
function outer()
{
result = 0;
for(i = 0; i  100; ++i)
{
result += inner(i);
}
return result
}
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
def ajax_profile(request, id):
entity = directory.models.Entity.objects.filter(id = int(id))[0]
if entity.is_invisible:
return HttpResponse(u'h2People, etc./h2')
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: �������
We can
then click on Entity (or Locations), and add an entity��
.
Warnings or important notes appear in a box like this.
Preface
[  ]
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 feedback@packtpub.com,
and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
suggest@packtpub.com.
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 for the book
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/support, 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.
Preface
[  ]
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 copyright@packtpub.com 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 questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
jQuery and Ajax Integration
in Django
We will be working with the leading Python web framework, Django, on the server
side, and jQuery-powered Ajax on the client side. During the course of this book, we
will cover the basic technologies and then see them come together in an employee
intranet photo directory that shares some Web 2.0 strengths.
There is more than one good JavaScript library; we will be working with jQuery,
which has reached acceptance as a standard lightweight JavaScript library. It might
be suggested that Pythonistas may find much to like in jQuery: jQuery, like Python,
was carefully designed to enable the developer to get powerful results easily.
In this chapter, we will:
Discuss Ajax as not a single technology but a technique which is overlaid on
other technologies
Cover the basic technologies used in Ajax JavaScript
Cover Hello, world! in a Django kickstart
Introduce the Django templating engine
Cover how to serve up static content in Django
Overall, what we will be doing is laying a solid foundation and introducing the
working pieces of Django Ajax to be explored in this book.
•
•
•
•
•
jQuery and Ajax Integration in Django
[  ]
Ajax and the XMLHttpRequest object
Ajax is not a technology like JavaScript or CSS, but is more like an overlaid function.
So, what exactly is that?
Human speech: An overlaid function
Human speech is an overlaid function. What is meant by this is reflected in the
answer to a question: What part of the human body has the basic job of speech?
The tongue, for one answer, is used in speech, but it also tastes food and helps us
swallow. The lungs and diaphragm, for another answer, perform the essential task
of breathing. The brain cannot be overlooked, but it also does a great many other
jobs. All of these parts of the body do something more essential than speech and,
for that matter, all of these can be found among animals that cannot talk. Speech
is something that is overlaid over organs that are there in the first place because of
something other than speech.
Something similar to this is true for Ajax, which is not a technology in itself,
but something overlaid on top of other technologies. Ajax, some people say,
stands for Asynchronous JavaScript and XML, but that was a retroactive expansion.
JavaScript was introduced almost a decade before people began seriously talking
about Ajax. Not only is it technically possible to use Ajax without JavaScript (one
can substitute VBScript at the expense of browser compatibility), but there are
quite a few substantial reasons to use JavaScript Object Notation (JSON) in lieu of
heavy-on-the-wire eXtensible Markup Language (XML). Performing the overlaid
function of Ajax with JSON replacing XML is just as eligible to be considered
full-fledged Ajax as a solution incorporating XML.
Ajax: Another overlaid function
What exactly is this overlaid function?
Ajax is a way of using client-side technologies to talk with a server and perform partial page
updates. Updates may be to all or part of the page, or simply to data handled behind
the scenes. It is an alternative to the older paradigm of having a whole page replaced
by a new page loaded when someone clicks on a link or submits a form. Partial
page updates, in Ajax, are associated with Web 2.0, while whole page updates are
associated with Web 1.0; it is important to note that Web 2.0 and Ajax are not
interchangeable. Web 2.0 includes more decentralized control and contributions
besides Ajax, and for some objectives it may make perfect sense to develop an
e-commerce site that uses Ajax but does not open the door to the same kind of
community contributions as Web 2.0.
Chapter 1
[  ]
Some of the key features common in Web 2.0 include:
Partial page updates with JavaScript communicating with a server and
rendering to a page
An emphasis on user-centered design
Enabling community participation to update the website
Enabling information sharing as core to what this communication allows
The concept of partial page updates may not sound very big, but part of its
significance may be seen in an unintended effect. The original expectation of partial
page updates was that it would enable web applications that were more responsive.
The expectation was that if submitting a form would only change a small area of a
page, using Ajax to just load the change would be faster than reloading the entire
page for every minor change. That much was true, but once programmers began
exploring, what they used Ajax for was not simply minor page updates, but making
client-side applications that took on challenges more like those one would expect a
desktop program to do, and the more interesting Ajax applications usually became
slower. Again, this was not because you could not fetch part of the page and update
it faster, but because programmers were trying to do things on the client side that
simply were not possible under the older way of doing things, and were pushing the
envelope on the concept of a web application and what web applications can do.
The technologies Ajax is overlaid on
Now let us look at some of the technologies where Ajax may be said to be overlaid.
JavaScript
JavaScript deserves pride of place, and while it is possible to use VBScript for
Internet Explorer as much more than a proof of concept, for now if you are
doing Ajax, it will almost certainly be Ajax running JavaScript as its engine. Your
application will have JavaScript working with XMLHttpRequest, JavaScript working
with HTML, XHTML, or HTML5; JavaScript working with the DOM, JavaScript
working with CSS, JavaScript working with XML or JSON, and perhaps JavaScript
working with other things.
•
•
•
•
jQuery and Ajax Integration in Django
[ 10 ]
While addressing a group of Django developers or Pythonistas, it would seem
appropriate to open with, I share your enthusiasm. On the other hand, while
addressing a group of JavaScript programmers, in a few ways it is more appropriate
to say, I feel your pain. JavaScript is a language that has been discovered as a gem,
but its warts were enough for it to be largely unappreciated for a long time. Ajax
is the gateway drug to JavaScript, as it has been said—however, JavaScript needs a
gateway drug before people get hooked on it. JavaScript is an excellent language and
a terrible language rolled into one.
Before discussing some of the strengths of JavaScript—and the language does have
some truly deep strengths—I would like to say I feel your pain and discuss two
quite distinct types of pain in the JavaScript language.
The first source of pain is some of the language decisions in JavaScript:
The Wikipedia article says it was designed to resemble Java but be easier for
non-programmers, a decision reminiscent of SQL and COBOL.
The Java programmer who finds the C-family idiom of for(i = 0; i  100;
++i) available will be astonished to find that the functions are clobbering
each other's assignments to i until they are explicitly declared local to the
function by declaring the variables with var. There is more pain where that
came from.
The following two functions will not perform the naively expected mathematical
calculation correctly; the assignments to i and the result will clobber each other:
function outer()
{
result = 0;
for(i = 0; i  100; ++i)
{
result += inner(i);
}
return result
}
function inner(limit)
{
result = 0;
for(i = 0; i  limit; ++i)
{
result += i;
}
return result;
}
•
•
Chapter 1
[ 11 ]
The second source of pain is quite different. It is a pain of inconsistent
implementation: the pain of, Write once, debug everywhere. Strictly speaking, this
is not JavaScript's fault; browsers are inconsistent. And it need not be a pain in the
server-side use of JavaScript or other non-browser uses. However, it comes along
for the ride for people who wish to use JavaScript to do Ajax. Cross-browser testing
is a foundational practice in web development of any stripe; a good web page with
semantic markup and good CSS styling that is developed on Firefox will usually look
sane on Internet Explorer (or vice versa), even if not quite pixel-perfect. But program
directly for the JavaScript implementation on one version of a browser, and you
stand rather sharp odds of your application not working at all on another browser.
The most important object by far for Ajax is the XMLHttpRequest and not only is it
not the case that you may have to do different things to get an XMLHttpRequest in
different browsers or sometimes different (common) versions of the same browser,
and, even when you have code that will get an XMLHttpRequest object, the objects
you have can be incompatible so that code that works on one will show strange bugs
for another. Just because you have done the work of getting an XMLHttpRequest
object in all of the major browsers, it doesn't mean you're home free.
Before discussing some of the strengths of the JavaScript language itself, it
would be worth pointing out that a good library significantly reduces the second
source of pain. Almost any sane library will provide a single, consistent way to get
XMLHttpRequest functionality, and consistent behavior for the access it provides.
In other words, one of the services provided by a good JavaScript library is a much
more uniform behavior, so that you are programming for only one model, or as
close as it can manage, and not, for instance, pasting conditional boilerplate code to
do simple things that are handled differently by different browser versions, often
rendering surprisingly different interpretations of JavaScript. We will be using the
jQuery library in this book as a standard, well-designed, lightweight library. Many
of the things we will see done well as we explore jQuery are also done well in
other libraries.
We previously said that JavaScript is an excellent language and a terrible language
rolled into one; what is to be said in favor of JavaScript? The list of faults is hardly all
that is wrong with JavaScript, and saying that libraries can dull the pain is not itself
a great compliment. But in fact, something much stronger can be said for JavaScript:
If you can figure out why Python is a good language, you can figure out why JavaScript is
a good language.
jQuery and Ajax Integration in Django
[ 12 ]
I remember, when I was chasing pointer errors in what became 60,000 lines of C,
teasing a fellow student for using Perl instead of a real language. It was clear in my
mind that there were interpreted scripting languages, such as the bash scripting that
I used for minor convenience scripts, and then there were real languages, which were
compiled to machine code. I was sure that a real language was identified with being
compiled, among other things, and that power in a language was the sort of thing C
traded in. (I wonder why he didn't ask me if he wasn't a real programmer because
he didn't spend half his time chasing pointer errors.) Within the past year or so I've
been asked if Python is a real programming language or is just used for scripting,
and something similar to the attitude shift I needed to appreciate Perl and Python is
needed to properly appreciate JavaScript.
The name JavaScript is unfortunate; like calling Python Assembler Kit, it's a
way to ask people not to see its real strengths. (Someone looking for tools for
working on an assembler would be rather disgusted to buy an Assembler Kit and
find Python inside. People looking for Java's strengths in JavaScript will almost
certainly be disappointed.)
JavaScript code may look like Java in an editor, but the resemblance is a façade;
besides Mocha, which had been renamed LiveScript, being renamed to JavaScript
just when Netscape was announcing Java support in web browsers, it is has been
described as being descended from NewtonScript, Self, Smalltalk, and Lisp, as well
as being influenced by Scheme, Perl, Python, C, and Java. What's under the Java
façade is pretty interesting. And, in the sense of the simplifying façade design
pattern, JavaScript was marketed in a way almost guaranteed not to communicate its
strengths to programmers. It was marketed as something that nontechnical people
could add snippets of, in order to achieve minor, and usually annoying, effects on
their web pages. It may not have been a toy language, but it sure was dressed up
like one.
Python may not have functions clobbering each other's variables (at least not
unless they are explicitly declared global), but Python and JavaScript are both
multiparadigm languages that support object-oriented programming, and their
versions of object-oriented have a lot in common, particularly as compared to (for
instance) Java. In Java, an object's class defines its methods and the type of its fields,
and this much is set in stone. In Python, an object's class defines what an object starts
off as, but methods and fields can be attached and detached at will. In JavaScript,
classes as such do not exist (unless simulated by a library such as Prototype), but
an object can inherit from another object, making a prototype and by implication
a prototype chain, and like Python it is dynamic in that fields can be attached and
detached at will. In Java, the instanceof keyword is important, as are class casts,
associated with strong, static typing; Python doesn't have casts, and its isinstance()
function is seen by some as a mistake, hence the blog posting isinstance()
considered harmful at http://www.canonical.org/~kragen/isinstance/.
Chapter 1
[ 13 ]
The concern is that Python, like JavaScript, is a duck-typing language: If it looks like
a duck, and it quacks like a duck, it's a duck! In a duck-typing language, if you write
a program that polls weather data, and there's a ForecastFromScreenscraper
object that is several years old and screenscrapes an HTML page, you should be
able to write a ForecastFromRSS object that gets the same information much more
cleanly from an RSS feed. You should be able to use it as a drop-in replacement as
long as you have the interface right. That is different from Java; at least if it were a
ForecastFromScreenscraper object, code would break immediately if you handed
it a ForecastFromRSS object. Now, in fairness to Java, the best practices Java
way to do it would probably separate out an IForecast interface, which would be
implemented by both ForecastFromScreenscraper and later ForecastFromRSS,
and Java has ways of allowing drop-in replacements if they have been explicitly
foreseen and planned for. However, in duck-typed languages, the reality goes
beyond the fact that if the people in charge designed things carefully and used
an interface for a particular role played by an object, you can make a drop-in
replacement. In a duck-typed language, you can make a drop-in replacement for
things that the original developers never imagined you would want to replace.
JavaScript's reputation is changing. More and more people are recognizing that
there's more to the language than design flaws. More and more people are looking
past the fact that JavaScript is packaged like Java, like packaging a hammer to give
the impression that it is basically like a wrench. More and more people are looking
past the silly toy language Halloween costume that JavaScript was stuffed into
as a kid.
One of the ways good programmers grow is by learning new languages, and
JavaScript is not just the gateway to mainstream Ajax; it is an interesting language
in itself. With that much stated, we will be making a carefully chosen, selective
use of JavaScript, and not make a language lover's exploration of the JavaScript
language, overall. Much of our work will be with the jQuery library; if you have just
programmed a little bare JavaScript, discovering jQuery is a bit like discovering
Python, in terms of a tool that cuts like a hot knife through butter. It takes learning,
but it yields power and interesting results soon as well as having some room
to grow.
jQuery and Ajax Integration in Django
[ 14 ]
XMLHttpRequest
The XMLHttpRequest object is the reason why the kind of games that can be
implemented with Ajax technologies do not stop at clones of Tetris and other games
that do not know or care if they are attached to a network. They include massive
multiplayer online role-playing games where the network is the computer. Without
having something like XMLHttpRequest, Ajax chess would probably mean a game
of chess against a chess engine running in your browser's JavaScript engine; with
XMLHttpRequest, Ajax chess is more likely man-to-man chess against another
human player connected via the network. The XMLHttpRequest object is the object
that lets Gmail, Google Maps, Bing Maps, Facebook, and many less famous Ajax
applications deliver on Sun's promise: the network is the computer.
There are differences and some incompatibilities between different versions
of XMLHttpRequest, and efforts are underway to advance level-2-compliant
XMLHttpRequest implementations, featuring everything that is expected of an
XMLHttpRequest object today and providing further functionality in addition,
somewhat in the spirit of level 2 or level 3 CSS compliance. We will not be looking
at level 2 efforts, but we will look at the baseline of what is expected as standard in
most XMLHttpRequest objects.
The basic way that an XMLHttpRequest object is used is that the object is created or
reused (the preferred practice usually being to reuse rather than create and discard
a large number), a callback event handler is specified, the connection is opened, the
data is sent, and then when the network operation completes, the callback handler
retrieves the response from XMLHttpRequest and takes an appropriate action.
A bare-bones XMLHttpRequest object can be expected to have the following methods
and properties.
Methods
A bare-bones XMLHttpRequest object can be expected to have the following methods:
1. XMLHttpRequest.abort()
This cancels any active request.
2. XMLHttpRequest.getAllResponseHeaders()
This returns all HTTP response headers sent with the response.
3. XMLHttpRequest.getResponseHeader(headerName)
This returns the requested header if available, or a browser-dependent false
value if the header is not defined.
Chapter 1
[ 15 ]
4. XMLHttpRequest.open(method, URL),
XMLHttpRequest.open(method, URL, asynchronous),
XMLHttpRequest.open(method, URL, asynchronous, username),
XMLHttpRequest.open(method, URL, asynchronous, username,
password)
The method is GET, POST, HEAD, or one of the other less frequently used
methods defined for HTTP.
The URL is the relative or absolute URL to fetch. As a security measure for
JavaScript running in browsers on trusted internal networks, a same origin
policy is in effect, prohibiting direct access to servers other than one the
web page came from. Note that this is less restrictive than it sounds, as it is
entirely permissible for the server to act as a proxy for any server it has
access to: for developers willing to undertake the necessary chores, other
sites on the public internet are virtually accessible.
The asynchronous variable defaults to true, meaning that the method call
should return quickly in most cases, instead of waiting for the network
operation to complete. Normally this default value should be preserved.
Among other problems, setting it to false can lock up the visitor's browser.
The last two arguments are the username and password as optionally
specified in HTTP. If they are not specified, they default to any username
and password defined for the web page.
5. XMLHttpRequest.send(content)
Content can be a string or a reference to a document.
Properties
A bare-bones XMLHttpRequest object can be expected to have the following
properties:
1. XMLHttpRequest.onreadystatechange,
XMLHttpRequest.readyState
In addition to the provided methods, the reference to one other method is
supplied by the developer as a property, XMLHttpRequest.onreadystate-
change, which is called without argument each time the ready state of
XMLHttpRequest changes. An XMLHttpRequest object can have five
ready states:
Uninitialized, meaning that open() has not been called.
Open, meaning that open() has been called but send() has not.
Sent, meaning that send() has been called, and headers and status
are available, but the response is not yet available.
°
°
°
jQuery and Ajax Integration in Django
[ 16 ]
Receiving, meaning that the response is being downloaded and
responseText has the portion that is presently available.
Loaded, meaning that the network operation has completed. If
it has completed successfully (that is, the HTTP status stored in
XMLHttpRequest.status is 200), this is when the web page would
be updated based on the response.
2. XMLHttpRequest.responseText, XMLHttpRequest.responseXML
The text of the response. It is important to note that while the name
XMLHttpRequest is now very well established, and it was originally
envisioned as a tool to get XML, the job done today is quite often to get text
that may or may not happen to be XML. While there have been problems
encountered with using XMLHttpRequest to fetch raw binary data, the
XMLHttpRequest object is commonly used to fetch not only XML but
XHTML, HTML, plain text, and JSON, among others. If it were being named
today, it would make excellent sense to name it TextHttpRequest. Once
the request reaches a ready state of 4 (loaded), the responseText field will
contain the text that was served up, whether the specific text format is XML
or anything else. In addition, if the format does turn out to be XML, the
responseXML field will hold a parsed XML document.
3. XMLHttpRequest.status, XMLHttpRequest.statusText
The status field contains the HTTP code, such as 200 for OK; the
statusText field has a short text description, like OK. The callback event
handler should ordinarily check XMLHttpRequest.readyState and wait
before acting on server-provided data until the readyState is 4. In addition,
because there could be a server error or a network error, the callback will
check whether the status is 200 or something else: a code like 4xx or 5xx in
particular needs to be treated as an error. If the server-response has been
transmitted successfully, the readyState will be 4 and the status will
be 200.
This is the basic work that needs to be done for the XMLHttpRequest side of Ajax.
Other frameworks may simplify this and do much of the cross-browser debugging
work for you; we will see in the next chapter how jQuery simplifies this work. But
this kind of task is something you will need to have done with any library, and
it's worth knowing what's behind the simplified interfaces that jQuery and other
libraries provide.
°
°
Chapter 1
[ 17 ]
HTML/XHTML
HTML and XHTML make up the bedrock markup language for the web. JavaScript
and CSS were introduced in relation to HTML; perhaps some people are now saying
that JavaScript is a very interesting language independent of web browsers and
using standalone interpreters such as SpiderMonkey and Rhino. However, HTML
was on the scene first and other players on the web exist in relation to HTML's
story. Even when re-implemented as XHTML, to do HTML's job while potentially
making much more sense to parsers, a very early web page, the beginning of the
source at http://www.w3.org/History/19921103-hypertext/hypertext/WWW/
TheProject.html, is still quite intelligible:
HEADER
TITLEThe World Wide Web project/TITLE
NEXTID N=55
/HEADER
BODY
H1World Wide Web/H1The WorldWideWeb (W3)
is a wide-area
A NAME=0 HREF=WhatIs.html
hypermedia/A information retrieval
initiative aiming to give universal
access to a large universe of documents.P
Everything there is online about
W3 is linked directly or indirectly
to this document, including an
A NAME=24 HREF=Summary.htmlexecutive
summary/A of the project,
A NAME=29 HREF=Administration/Mailing/Overview.html
Mailing lists/A ,
A NAME=30 HREF=Policy.htmlPolicy/A , November's
A NAME=34 HREF=News/9211.htmlW3 news/A ,
A NAME=41 HREF=FAQ/List.htmlFrequently Asked Questions
/A .
DL
…
At the time of this writing, HTML 5 is taking shape but is not out in the wild, and
so there are no reports of how the shoe feels after the public has worn it for a while.
Code in this book, where possible, will be written in XHTML 1.0 Strict. Depending
on your situation, this may or may not be the right decision for you; if you are
working with an existing project, the right HTML/XHTML is often the one that
maintains consistency within the project.
jQuery and Ajax Integration in Django
[ 18 ]
XML
eXtensible Markup Language (XML) is tied to an attempt to clean up early
HTML. At least in earliest forms, HTML was a black sheep among specific markup
languages derived from the generalized and quite heavy Standard Generalized
Markup Language (SGML). Forgiving web browsers meant, in part, that early web
hobbyists could write terrible markup and it would still display well in a browser.
The amount of terrible markup on the web was not just an issue for purists; it
meant that making a parser that could make sense of early Wild West web pages
in general was a nearly impossible task. XML is vastly simplified from SGML, but
it provides a generic space where an HTML variant, XHTML, could pick up the
work done by HTML but not present parsers with unpredictable tag soup. XHTML
could be described as HTML brought back into the fold, still good for doing web
development, but without making machine interpretation such a hopeless cause.
Where early HTML was developed with browsers that were meant to be forgiving,
XML requested draconian error handling, and validated XML or XHTML documents
are documents that can be parsed in a sensible way.
XML works for exchanging information, and it works where many of its
predecessors had failed: it provides interoperability between different systems after a
long history of failed attempts at automating B2B communication and failed attempts
at automated conversion between text data formats. Notwithstanding this, it is a
heavy and verbose solution, with a bureaucratic ambiance, compared in particular
to a lean, mean JSON. XML-based approaches to data storage and communication
are increasingly critiqued in discussions on the web. If you have a reasonable choice
between XML and JSON, we suggest that you seriously consider JSON.
JSON
JavaScript Object Notation (JSON) is a brilliantly simple idea. While formats like
XML, ReStructuredText, and so on share the assumption that if you're going to
parse this from your language, your language will need to have a parser added,
JSON simply takes advantage of how an object would be specified in JavaScript,
and clarifies a couple of minor points to make JSON conceptually simpler and
cross-browser friendly. JSON is clear, simple, and concise enough that not only is it
a format of choice for JavaScript, but it is gaining traction in other languages, and it
is being used for communication between languages that need a (simple, added)
parser to parse JSON. The other languages can't use eval() to simply run JSON,
and in JavaScript you should have JSON checked to make sure it does not contain
malicious JavaScript you should not eval(). However, JSON is turning out to have
a much broader impact than the initial in communicating with JavaScript, just give
it code to declare the object being communicated that can simply be evaluated
to construct the object.
Chapter 1
[ 19 ]
CSS
Cascading Style Sheets (CSS) may have introduced some new possibilities for
presentation, but quite a lot of presentation was already possible beforehand. CSS
did not so much add styling capabilities, as it added good engineering to styling
(good engineering is the essence of separating presentation from content), and
make the combination of semantic markup and attractive appearance a far more
attainable goal. It allows parlor tricks such as in-place rebranding of websites:
making changes in images and changing one stylesheet is, at least in principle,
enough to reskin an extensive website without touching a single character of its
HTML/XHTML markup. In Ajax, as for the rest of the web, the preferred practice is
to use semantic, structural markup, and then add styles in a stylesheet (not inline)
so that a particular element, optionally belonging to the right class or given the right
ID, will have the desired appearance. Tables are not deprecated but should be used
for semantic presentation of tabular data where it makes sense to use not only a td
but a th as well. What is discouraged is using the side effect that tables can position
content that is not, semantically speaking, tabular data.
The DOM
As far as direct human browsing is concerned, HTML and associated technologies
are vehicles to deliver a pickled Document Object Model (DOM), and nothing
more. In this respect, HTML is a means to an end: the DOM is the deserialized
object, or better, the live form of what we really deliver to people. HTML may
help provide a complete blueprint, and the complete blueprint is a means to the
fully realized building. This is why solving Ajax problems on the level of HTML
text are like answering the wrong question, or at least solving a problem on the
wrong level. It is like deciding that you want a painting hung on a wall of a building,
and then going about getting it by adding the painting to the blueprint and asking
construction personnel to implement the specified change. It may be better to hang
the painting on the wall directly, as is done in Ajax DOM manipulations.
document.write() and document.getElementById().innerHTML() still have
a place in web development. It is a sensible optimization to want a static, cacheable
HTML/XHTML file include that will only be downloaded once in the usual
multi-page visit. A JavaScript include with a series of document.write() may be
the least Shanghaiing you can do to technologies and still achieve that goal. But this
is not Ajax; it is barely JavaScript, and this is not where we should be getting our
bearings. In Ajax, a serious alternative to this kind of solution for altering part of a
web page is with the DOM.
As the book progresses, we will explore Ajax development that works with
the DOM.
jQuery and Ajax Integration in Django
[ 20 ]
iframes and other Ajax variations
Ajax includes several variations; Comet for instance, is a variation on standard Ajax
in which either an XMLHttpRequest object's connection to a server is kept open
and streaming indefinitely, or a new connection is opened whenever an old one is
closed, creating an Ajax environment in which the server as well as the client can
push material. This is used, for instance, in some instant messaging implementations.
One much more essential Ajax variation has to do with loading documents into
seamlessly integrated iframes instead of making DOM manipulations to a single,
frame-free web page.
If you click around on the page for a Gmail account, you will see partial page
refreshes that look consistent with Ajax DOM manipulations: what happens when
you click on Compose Mail, or a filter, or a message subject, looks very much like
an Ajax update where the Gmail web application talks with the server if it needs to,
and then updates the DOM in accordance with your clicks. However, there is one
important difference between Gmail's behavior and a similar Ajax clone that updates
the DOM for one frameless web page: what happens when you click the browser
Back button. Normally, if you click on a link, you trigger an Ajax event but not a
whole page refresh, and Ajax optionally communicates with a server and updates
some part of the DOM. This does not register in the browser's history, and hitting the
Back button would not simply reset the last Ajax partial page update. If you made an
Ajax clone of Gmail that used DOM manipulations instead of seamlessly integrated
iframes, there would be one important difference in using the clone: hitting Back
would do far more than reverse the last DOM manipulation. It would take you back
to the login or load screen. In Gmail, the browser's Back button works with surgical
accuracy, and the reason it can do something much better than take you back to the
login screen is that Gmail is carefully implemented with iframes, and every change
that the Back button can undo is implemented by a fresh page load in one of the
seamlessly integrated iframes. That creates browsing history.
For that matter, a proof of concept has been created for an Ajax application that
does not use client-side scripting or programming, instead using, on the client side,
a system of frames/iframes, targets, links, form submissions, and meta refresh tags
in order to perform partial page updates. Whether this variant technique lends
itself to creating graceful alternatives to standard Ajax implementations, or is only
a curiosity merely lending itself to proofs of concept, it is in principle possible to
make an Ajax application that loses nothing if a visitor's browser has turned off
scripting completely.
Comet and iframes are two of many possible variations on the basic Ajax technique;
what qualifies as Ajax is more a matter of Python- or JavaScript-style duck-typing
than Java-style static typing. Asynchronous JavaScript and XML describes a
reference example more than a strict definition, and it is not appropriate to say if
Chapter 1
[ 21 ]
you replace XML with JSON then, by definition, it isn't really Ajax. This is a case of,
the proof of the pudding is in the eating, not what technologies or even techniques
are in the kitchen.
JavaScript/Ajax Libraries
This book advocates taking advantage of libraries, and as a limitation of scope
focuses on jQuery. If you only learn one library, or if you are starting with just one
library, jQuery is a good choice, and it is widely used. It is powerful, but it is also a
much easier environment to get started in than some other libraries; in that way, it is
somewhat like Python. However, it is best not to ask, Which one library is best?
but Which library or libraries are the right tools for this job?, and it is common
real-world practice to use more than one library, possibly several.
JavaScript libraries offer several advantages. They can reduce chores and boilerplate
code, significantly lessening the pain of JavaScript, and provide a more uniform
interface. They can also provide (for instance) ready-made widgets; we will be
working with a jQuery slider later on in this book. And on a broad scale, they
can let the JavaScript you write be higher-level and a little more Pythonic.
Server-side technologies
Many of the usual suspects in client-side technologies have been mentioned.
The list of client-side technologies is generally constrained by what is available
in common web browsers; the list of available server-side technologies is only
constrained by what will work on the server, and any general-purpose programming
language can do the job. The question on the server is not What is available? but
Which option would you choose? Python and Django make an excellent choice
of server-side technology, and we will work with them in this book.
A look at Django
Django's developers call it the web framework for perfectionists with deadlines,
and it is one of the most popular Python web frameworks, perhaps the most popular.
In contrast to the MVC pattern, which separates concerns into Model, View, and
Controller, it could be described as an MTV pattern, which separates concerns into
Model, Template, and View. The Model is a class that ties into an ORM where
instances correspond to rows in the table but act and feel like Python objects. The
Template is a system designed to be easy for non-Python developers (though easy
for Pythonistas too), and limits the extent to which HTML needs to be sprinkled
throughout the Python source. The View is a function that renders, in most cases,
from a template. Let's look at a kickstart example of Django in action.
jQuery and Ajax Integration in Django
[ 22 ]
Django templating kickstart
Let us briefly go through how to install Django, create a sample project, and create
and use a basic template that can serve as a basis for further tinkering.
Django installation instructions are at http://docs.djangoproject.com/en/dev/
intro/install/; for Ubuntu, for instance, you will want to run sudo apt-get
install python-django.
Once you have Django installed, create a project named sample:
django-admin.py startproject sample
Go into the sample directory, and create the directory templates. Enter the
templates directory.
Create a template file named index.html containing the following template:
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www.
w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US
lang=en-US
head
title{% block title %}Hello, world!{% endblock title %}
/title
meta http-equiv=Content-Type content=text/html;
charset=UTF-8 /
/head
body
{% block body %}
h1{% block heading %}Hello, world!
{% endblock heading %}/h1
{% block content %}pGreetings from the Django
templating engine!/p{% endblock content %}
{% endblock body %}
/body
/html
Go up one level to the sample directory and edit the urls.py file so that the first line
after urlpatterns = patterns('', is:
(r'^$', 'sample.views.home'),
Then create the views.py file containing the following:
#!/usr/bin/python/
from django.shortcuts import render_to_response
def home(request):
return render_to_response(u'index.html')
Chapter 1
[ 23 ]
Edit the settings.py file, and add:
os.path.join(os.path.dirname(__file__), templates),
right after:
TEMPLATE_DIRS = (
Then, from the command line, run:
python manage.py runserver
This makes the server accessible to your computer only by entering the URL
http://localhost:8080/ in your web browser.
If you are in a protected environment behind a firewall, appropriate NATting, or the
like, you can make the development server available to the network by running:
python manage.py runserver 0.0.0.0:8080
There is one point of clarification we would like to make clear. Django is packaged
with a minimal, single-threaded web server that is intended to be just enough to start
exploring Django in a development environment. Django's creators are attempting to
make a good, competitive web framework and not a good, competitive web server,
and the development server has never undergone a security audit. The explicit advice
from Django's creators is: when deploying, use a good, serious web server; they also
provide instructions for doing this.
A more complete glimpse at Django templating
Before further exploring technical details, it would be worth taking a look at the
opinions and philosophy behind the Django templating language, because an
understandable approach of, Oh, it's a general purpose programming language
used for templating, is a recipe for needless frustration and pain. The Django
developers themselves acknowledge that their opinions in the templating language
are one just opinion in an area where different people have different opinions, and
you are welcome to disagree with them if you want. If you don't like the templating
system that Django comes with, Django is designed to let you use another. But
it is worth understanding what exactly the philosophy is behind the templating
language; even if this is not the only philosophy one could use, it is carefully
thought out.
jQuery and Ajax Integration in Django
[ 24 ]
The Django templating language is intended to foster the separation of presentation
and logic. In its design decisions, both large and small, Django's templating engine
is optimized primarily for designers to use for designing, rather than programmers
to use for programming, and its limitations are almost as carefully chosen as the
features it provides. Unlike ASP, JSP, and PHP, it is not a programming language
interspersed with HTML. It provides enough power for presentation, and is intended
not to provide enough power to do serious programming work where it doesn't
belong (in the Django opinion), and is simple enough that some non-programmers
can pick it up in a day. For a programmer, the difficulty of learning the templating
basics is comparable to the difficulty of simple HTML or SQL: it is simple, and a
good bit easier to learn than wrapping your arms around a regular programming
language. Some programmers like it immediately, but there are some who started by
asking, Why doesn't the templating language just let you mix Python and HTML?
and after playing with it, found themselves saying, This isn't what I would have
come up with myself, but I really, really like it.
Additional benefits include it being fast (most of the work is done by a single regular
expression call, and the founders talk about disabling caching because it wasn't
as fast as the template rendering), secure (it is designed so that it can be used by
untrusted designers without allowing a malicious designer to execute arbitrary
code), and versatile enough to generate whatever text format you want: plain text,
HTML, XML, XHTML, JSON, JavaScript, CSV, ReStructuredText, and so on. We will
be using it to generate web pages and JSON, but Django's templating language is a
general-purpose text templating solution.
Following the Django site's lead, let us use a template intended as an example
of how one might begin a base template for a site, then start to walk through its
contents, and then look at some of how it could be used and parts overridden
to create a specific document.
This renders as follows, if we strip out blank lines:
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www.
w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US
lang=en-US
head
title/title
link rel=icon href=/https/www.slideshare.net/static/favicon.ico
type=x-icon /
link rel=shortcut icon href=/https/www.slideshare.net/static/favicon.ico
type=x-icon /
meta http-equiv=Content-Type content=text/html;
charset=UTF-8 /
meta http-equiv=Content-Language value=en-US /
Chapter 1
[ 25 ]
link rel=stylesheet type=text/css
href=/https/www.slideshare.net/static/css/style.css /
/head
body
div id=sidebar
/div
div id=content
div id=header
h1/h1
/div
/div
div id=footer
/div
/body
script language=JavaScript type=text/javascript
src=/static/js/jquery.js/script
/html
Let us unwrap what is going on here; there is more to the template than how it
renders to this page, but let us start with that much.
The {% block dtd %} style tags begin, or the case of {% endblock dtd %} end, a
semantic block of text that can be left untouched or can be replaced. In the case of
this one template, the effect is to strip them out like comments, but they will yield
benefits later on, much like semantic HTML markup with CSS yields benefits
later on.
Django templating reflects a choice to go with hooks rather than includes because
hooks provide the more versatile solution. The beginner's mistake version of
a header to include might be something like the following:
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www.
w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US
lang=en-US
head
titleWelcome to my site!/title
link rel=icon href=/https/www.slideshare.net/favicon.ico type=x-icon /
link rel=shortcut icon href=/https/www.slideshare.net/favicon.ico
type=x-icon /
meta http-equiv=Content-Type content=text/html;
charset=UTF-8 /
meta http-equiv=Content-Language value=en-US /
link rel=stylesheet type=text/css
href=/https/www.slideshare.net/css/style.css /
/head
body
jQuery and Ajax Integration in Django
[ 26 ]
This solution could be continued by adding a sidebar, but there is a minor problem,
or at least it seems minor at first: there are bits of this header that are not generic.
For a serious site, having every page titled, Welcome to my site! would be an
embarrassment. The language is declared to be en-US, meaning U.S. English, which
is wonderful if the entire site is in U.S. English, but if it expands to include more than
U.S. English content, hardcoding en-US will be a problem. If the only concern is to
accurately label British English, then the more expansive en could be substituted in,
but hardcoding en-US and en are equally unhelpful if the site expands to feature
a section in Russian. This header does not include other meta tags that might be
desirable, such as description, which is ideally written for a specific page and not
done as site-wide boilerplate. Including the header verbatim solves a problem, but it
doesn't provide a very flexible solution.
The previous example builds in hooks. It does specify:
{% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml:
lang=en-US lang=en-US{% endblock html_tag %}
If not overridden, this will render as:
html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US
lang=en-US
However, in a template that extends this, by having {% extends base.html %} as
its opening tag, if the base is loaded as base.html, then:
{% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml:
lang=en-GB lang=en-GB{% endblock html_tag %}
will render:
html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-GB
lang=en-GB
And Russian may be declared in the same way:
{% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml:
lang=ru-RU lang=ru-RU{% endblock html_tag %}
will render:
html xmlns=http://www.w3.org/1999/xhtml xml:lang=ru-RU
lang=ru-RU
The template as given does specify en-US more than once, but each of these is
inside a block that can be overridden to specify another language.
Chapter 1
[ 27 ]
We define initial blocks. First, the DTD:
{% block dtd %}!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//
EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
{% endblock dtd %}
Then, the HTML tag:
{% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml:
lang=en-US lang=en-US{% endblock html_tag %}
Then we define the head, with the title and favicon:
{% block head %}head
title{% block title %}{{ page.title }}
{% endblock title %}/title
{% block head_favicon %}link rel=icon
href=/https/www.slideshare.net/static/favicon.ico type=x-icon /
link rel=shortcut icon href=/https/www.slideshare.net/static/favicon.ico
type=x-icon /{% endblock head_favicon %}
Then we define hooks for meta tags in the head. We define a Content-Type of UTF-8;
this is a basic point so that non-ASCII content will display correctly:
{% block head_meta %}
{% block head_meta_author%}{% endblock head_meta_author %}
{% block head_meta_charset %}
meta http-equiv=Content-Type content=text/html;
charset=UTF-8 /
{% endblock head_meta_charset %}
{% block head_meta_contentlanguage %}
meta http-equiv=Content-Language value=en-US /
{% endblock head_meta_contentlanguage %}
{% block head_meta_description %}
{% endblock head_meta_description %}
{% block head_meta_keywords %}
{% endblock head_meta_keywords %}
{% block head_meta_othertags %}
{% endblock head_meta_othertags %}
{% block head_meta_refresh %}
{% endblock head_meta_refresh %}
{% block head_meta_robots %}
{% endblock head_meta_robots %}
{% endblock head_meta %}
We declare a block to specify an RSS feed for the page:
{% block head_rss %}{% endblock head_rss %}
jQuery and Ajax Integration in Django
[ 28 ]
We add hooks for CSS, both at the site level, and section, and page. This allows
a fairly fine granularity of control:
{% block head_css %}
{% block head_css_site %}
link rel=stylesheet type=text/css
href=/https/www.slideshare.net/static/css/style.css /
{% endblock head_css_site %}
{% block head_css_section %}
{% endblock head_css_section %}
{% block head_css_page %}{% endblock head_css_page %}
{% endblock head_css %}
We add section- and page-specific header information:
{% block head_section %}{% endblock head_section %}
{% block head_page %}{% endblock head_page %}
Then we close the head and open the body:
/head{% endblock head %}
{% block body %}
body
We define a sidebar block, with a hook to populate it:
div id=sidebar
{% block body_sidebar %}{% endblock body_sidebar %}
/div
We define a block for the main content area:
div id=content
{% block body_content %}
For the header of the main content area, we define a banner hook, and a header for
the page's title, should such be provided. (If none is provided, there is no crash or
error; the empty string is displayed for {{ page.title }}.)
div id=header
{% block body_header %}
{% block body_header_banner %}
{% endblock body_header_banner %}
{% block body_header_title %}h1
{{ page.title }}/h1
{% endblock body_header_title %}
Chapter 1
[ 29 ]
We define a breadcrumb, which is one of many small usability touches that can
be desirable:
{% block body_header_breadcrumb %}
{{ page.breadcrumb }}
{% endblock body_header_breadcrumb %}
{% endblock body_header %}
/div
We add a slot for announcements, then the body's main area, and then close the
block and div:
{% block body_announcements %}
{% endblock body_announcements %}
{% block body_main %}{% endblock body_main %}
{% endblock body_content %}
/div
We define a footer div, with a footer breadcrumb, and a hook for anything our
company's lawyers asked us to put:
div id=footer
{% block body_footer %}
{% block body_footer_breadcrumb %}
{{ page.breadcrumb }}
{% endblock body_footer_breadcrumb %}
{% block body_footer_legal %}
{% endblock body_footer_legal %}
{% endblock body_footer %}
Now we close that div, the body, and the body block:
/div
/body{% endblock body %}
We add a footer, with JavaScript blocks, again at the site/section/page level
of hooks:
{% block footer %}
{% block footer_javascript %}
{% block footer_javascript_site %}
script language=JavaScript type=text/javascript
src=/static/js/jquery.js/script
{% endblock footer_javascript_site %}
{% block footer_javascript_section %}
{% endblock footer_javascript_section %}
{% block footer_javascript_page %}
jQuery and Ajax Integration in Django
[ 30 ]
{% endblock footer_javascript_page %}
{% endblock footer_javascript %}
{% endblock footer %}
/html
And that's it.
You can make as many layers of templates as you want. One suggested approach
is to make three layers: one base template for your entire site, then more specific
templates for sections of your site (whatever they may be), and then individual
templates for end use. The template given is a base template, and it provides
hooks as narrow as a specific meta tag or as broad as the main content area.
For our extended example, if it is named base.html, then we can create another
template, russian.html, which will declare its content to be in the Russian
language. (Ordinarily one would do more interesting things in overriding a template
than merely replacing tags, but for illustration purposes we will do that, and
only that:
{% extends base.html %}
{% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml:
lang=ru-RU lang=ru-RU{% endblock html_tag %}
{% block head_meta_contentlanguage %}meta http-equiv=Content-
Language value=ru-RU /{% endblock head_meta_contentlanguage %}
These block overrides may occur anywhere; while the {% extends base.html %}
tag must be placed first, the two tags may be swapped. It would work just as well
to create a language-agnostic base.html with only an empty hook:
{% block head_meta_contentlanguage %}
{% endblock head_meta_contentlanguage %}
and a default HTML tag of:
html xmlns=http://www.w3.org/1999/xhtml
And then create english.html and russian.html, or en-US.html and ru-RU.html,
as base templates for those languages.
However, there are many other tags than those used for blocks and overriding. We
will just barely sample them below, looking at how to display variables, and then
other tags.
Chapter 1
[ 31 ]
There are other tags that look like {% … %}, but I would comment briefly on the
variable tags such as {{ page.title }}. The Django templating language uses
dotted references, but not in exactly the same way as Python's dotted references.
Where Python requires a couple of different things to get values, dotted references
provide one-stop shopping in Django's templating. When a reference to {{ page.
title }} occurs, it will display page[u'title'] if page[u'title'] is available. If
not, it will display page.title if page.title is available as an attribute, and if there
is no such attribute, it will display page.title() if page.title() is available, and
failing that, if the reference is a non-negative integer like 2, it will display page[2]
if page.2 is requested. If all of these fail, then Django defaults to the empty string
because it's not acceptable for a professional site to crash because a programming
error has the template asking for something that is not available. You can override
the empty string by setting TEMPLATE_STRING_IF_INVALID in your settings.py
file, and in development it may make sense to set TEMPLATE_STRING_IF_INVALID to
something like LOOKUP FAILED, but you will want to set it back to the empty string
for deployment in any production environment.
At this point, while there are explicit hooks to pull in multiple JavaScript and
CSS files, the preferred practice, per Steve Souders's ground rules for client-side
optimizations for high performance websites, is: for each page to load initially, you
should have one HTML/XHTML page, one CSS file included at the top, and one
JavaScript file included at the bottom. The hooks are more flexible than that, but this
is intended more as development leeway than what the tightened final product
should be.
If-then, if-then-else statements, and for loops are straightforward, and else clauses
are optional:
{% if results %}
ul
{% for result in results %}
li{% result.title %}/li
{% endfor %}
/ul
{% else %}
pThere were no results./p
{% endif %}
There are a number of convenience features and minor variations available; these are
several of the major features.
jQuery and Ajax Integration in Django
[ 32 ]
Setting JavaScript and other static
content in place
For the development server, putting static content, including images, CSS, and static
content, is straightforward. For production use, the recommended best practice is
to use a different implementation, and Django users are advised to use a separate
server if possible, optimized for serving static media, such as a stripped-down build of
Apache, or nginx. However, for development use, the following steps will serve up
static content:
1. Create a directory named static within your project. (Note that other
names may be used, but do not use media, as that can collide with
administrative tools.)
2. Edit the settings.py file, and add the following at the top, after import os:
DIRNAME = os.path.abspath(os.path.dirname(__file__))
3. Change the settings of MEDIA_ROOT and MEDIA_URL:
MEDIA_ROOT = os.path.join(DIRNAME, 'static/')
…
MEDIA_URL = '/static/'
4. At the end of the settings.py file, add the following:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'^%s(?Ppath.*)$' % (settings.MEDIA_URL[1:],), 'serve', {
'document_root': settings.MEDIA_ROOT,
'show_indexes': True }),)
This will turn off static media service when DEBUG is turned off, so that this code
does not need to be changed when your site is deployed live, but the subdirectory
static within your project should now serve up static content, like a very simplified
Apache. We suggest that you create three subdirectories of static: static/css,
static/images, and static/js, for serving up CSS, image, and JavaScript
static content.
Chapter 1
[ 33 ]
Summary
Guido van Rossum, the creator of the Python programming language, for one
project asked about different Python frameworks and chose the Django templating
engine for his purposes (http://www.artima.com/weblogs/viewpost.
jsp?thread=146606). This chapter has provided an overview of Ajax and then
provided a kickstart introduction to the Django templating engine. There's more
to Django than its templating engine, but this should be enough to start exploring
and playing.
In learning a new technology, a crucial threshold has been passed when there is
enough of a critical mass of things you can do with a technology to begin tinkering,
and taking one step often invites the question: What can we do to take this one step
further?. In this chapter, we have provided a kickstart to begin working with the
Django templating engine.
In this chapter, we have looked at the idea of Pythonic problem solving, discussed
Django and jQuery in relation to Pythonic problem solving, and discussed Ajax as
not a single technology, but an overlaid function or technique that is overlaid on top
of existing technologies. We have taken an overview of what the usual suspect
technologies are for Ajax; given a kickstart to the Django templating engine,
introducing some of its beauty and power; and addressed a minor but important
detail: putting static content in place for Django's development server.
This is meant to serve as a point of departure for further discussion of jQuery Ajax
in the next chapter, and building our sample application. Interested readers who
want to know more of what they can do can read the official documentation at
http://docs.djangoproject.com/en/dev/topics/templates/.
In the next chapter, we will push further and aim for a critical mass of things we can
do. We will explore jQuery, the most common JavaScript library, and begin to see
how we can use it to reach the point of tinkering, of having something that works
and wondering, What if we try this?, What if we try that?, and being able to do it.
Random documents with unrelated
content Scribd suggests to you:
And now what must be the consequence? A derangement of
business which it is difficult to imagine, a contraction of currency
instantaneous and spasmodic to the amount of these large sums
that I have indicated.
I do not shrink from contraction. I am ready to say to the people
of Massachusetts, “If the Senate will adopt any policy of contraction
that is healthy, well-considered, and with proper conditions, I would
recommend its acceptance.” But a contraction like that proposed by
this bill, which arbitrarily takes from North and East this vast
amount, and transfers it to another part of the country, where it may
not be needed, such a contraction I oppose as mischievous. I see no
good in it. I see a disturbance of all the channels of business; and I
see a contraction which must be itself infinitely detrimental to the
financial interests of the Republic.
But then, Sir, have you considered whether you can do it? Is it
practicable? I have shown that it is mischievous: is it practicable?
Can you take this large amount of currency from one part of the
country and transfer it to another? Have you ever reflected upon the
history of the bank-note after it has commenced its travels, when it
has once left the maternal bank? It goes you know not where. I
have been informed by bank-officers, and by those most familiar
with such things, that a bank-note, when once issued, very rarely
returns home. I have been assured that it is hardly ever seen again.
The banks, indeed, may go into liquidation, but their notes are still
current. The maternal bank may be mouldering in the earth; but
these its children are moving about, performing the work of
circulation. Why? The credit of the nation is behind them; and
everybody knows, when he takes one of them, that he is safe.
Therefore, I ask, how can the proposed requirement be carried into
execution? how can you bring back these runaways, when once in
circulation on their perpetual travels?
There is but one way, and that is by the return to specie
payments. Hold up before them coin, and they will all come running
back to the original bank; but until then they will continue abroad.
The proposed requirement seems to go on the idea that bank-notes,
like cows, return from pasture at night; whereas we all know, that,
until specie payments, they are more like the wild cattle of the
prairies and the pampas; you cannot find them; they are
everywhere. Surely I am not wrong, when I suggest that the
proposed requirement is impracticable as well as mischievous; and
at the proper time I shall move to strike it out.
The amendment which I have moved has been under discussion
for several days. It has had the valuable support of the Senator from
Michigan [Mr. Chandler], who brings to financial questions practical
experience. It has been opposed by other Senators, and with
considerable ardor by my excellent friend from Indiana [Mr. Morton].
On Thursday last, the Senator from Indiana, addressing himself to
me, and inviting a reply, which I was then prevented from making,
took issue with me directly upon the position I have assumed, that
the withdrawal of legal-tender notes would materially assist the
effort for specie payments; and he further declared that the two
currencies of bank-notes and United States notes were kept together
because one was redeemable with the other. I do not quote his
precise words, but I give the substance.[220]
Under the policy we are now pursuing, it seems to me, that, with
$356,000,000 of legal-tender notes in circulation, the Government
will not for many years, if ever again, pay specie. With that amount
of United States notes, under the actual policy, the bank currency
will forever remain inconvertible. And the correctness of these
positions I will endeavor briefly to demonstrate.
A convertible currency is nothing more nor less than the servant of
coin. If there is no coin, it can neither be servant nor representative,
though it may attempt to perform the functions of coin. Presenting
itself under false pretences, it but partially succeeds in this attempt;
and the discredit attaching to it compels it to pay more for any
property than would be the price of such property in coin, or the
acknowledged representative of coin,—just as doubtful people must
submit to ten, fifteen, or twenty per cent. discount, when what is
known as “gilt-edged” commercial paper is discounted at five, six, or
seven per cent. Thus far we have had no coin in the Treasury
appropriated to the stability of the United States notes,—and under
our present policy, dictated by the restrictive laws that hedge the
Secretary of the Treasury and confine his liberty of action, we never
shall have, until the whole bonded debt of the country is
extinguished,—while at the same time the banks are excused under
the law from all attempts to fortify their notes with coin.
And what is it that successfully discourages us from direct steps
toward specie payments?
In the first place, it is the mistrust of the people in our ability to
resume, and to maintain resumption. In the next place, the monthly
publication of the Treasury discloses precisely our weakness as well
as our strength; and the great element of our weakness is the
volume of our past-due and demand obligations. In ordinary times,—
that is, when the people have confidence in the ability of the banks
to redeem their demand obligations in coin,—a reserve of twenty to
twenty-five per cent. in coin is more than sufficient to meet any
probable demand that may be made. Let mistrust arise in relation to
the solvency of any bank or of the system of banks, and the reserve
of twenty-five per cent. will vanish as the dew before the sun, and
the individual bank or all the banks must close their doors to all
demands for specie.
In our present legislation we encounter this mistrust wide-spread
among the people; and so long as we ourselves exhibit so great
timidity in our attempts at legislation upon this subject, just so long
do we minister to and strengthen this mistrust.
The amount of demand obligations which the Treasury must be
prepared to meet upon a moment’s notice, including three per cent.
certificates and fractional currency, is more than four hundred and
forty million dollars. With the existing mistrust, measured by the
premium on gold, a reserve of twenty-five per cent. of coin in the
Treasury appropriated to these demands would be totally
insufficient. This reserve must bear a proportion to the aggregate of
liabilities so large as to remove mistrust, and this can be
accomplished only by presenting as in the vaults of the Treasury an
amount of coin nearly equal to the sum of liabilities.
If during the last three years we had retained the surplus of coin
that has reached the Treasury, we should now have enough; but, as
a consequence of such accumulation, speculation would have run
riot,—and I fear, if we should now by legislative enactment decree
that course for the future, we should aggravate the situation.
What, then, is left for us to do? What but to lessen our liabilities?
—which, as the laws now stand, must remain the same to-morrow
as to-day, and one, two, or five years hence immutably as now.
Difficulties beset the contraction of those liabilities, as there are
difficulties that impede the accumulation of coin in sufficient amount
to meet our purpose; but the former may be neutralized, if not
removed, by judicious compensations that will not in any serious
degree retard the object for which I would legislate.
Sound financial authorities unite in declaring, that, if the
Government resumes specie payments, the banks of New York can
resume; and when the banks of New York resume, the whole
country can resume. Evidently, then, our care is the Government.
And what is the first step? To my mind we must lessen the
demand obligations of the Government, while the Secretary of the
Treasury at the same time strengthens the reserves in the national
vaults. Neither should be done suddenly or violently, but gradually,
judiciously, and wisely. As the statutes now stand, the obligations
cannot be reduced. With the present volume of obligations, the laws
of trade prevent the Secretary of the Treasury from sufficiently
strengthening his reserves. It therefore devolves upon the National
Legislature to take the initiative in the effort to resume specie
payments.
The difficulties that impede the reduction of the national liabilities
lie in the fact that such obligations are a part, and a large part, of
the currency of the country. To withdraw that currency without
giving a substitute is to create stringency, burden trade, and invite
chaos: at least, so it seems. These obligations, so far as they relate
to the currency, are larger in amount than those of the national
banks combined; and furthermore, they are the head and front of
all. They are so large as to be beyond the point of manageability,
and I would therefore reduce them within control. It is their volume
that puts them beyond control, and it is our want of control that
causes them to be depreciated. Thus, Sir, I would offer inducements
to fund them, or part of them, in bonds that would be sought after
because of their valuable uses beyond a mere investment, and to
neutralize the evils of contraction of Treasury liabilities by authorizing
their assumption, with the consent of the people, by various parties
in different sections of the country, each one of whom would be fully
equal to the task thus voluntarily assumed. I would issue a bank-
note for every dollar of Treasury obligation cancelled; but I would
issue no bank-note that did not absorb an equal obligation of the
Treasury. By this distribution of a portion of the demand obligations
you restore to the Government the full ability to meet the remainder;
and at the same time the people know, that, so far as the currency
goes,—and it is of this only we are treating,—every promise of any
bank has its ultimate recourse in the Treasury of the United States.
The absorption of one hundred and fifty or two hundred millions
cannot fail to enhance the remaining legal-tender nearly, if not quite,
to par with gold. The volume of currency in the channels of trade
and in the hands of the people will be about the same as now. The
aggregate of United States notes and national bank-notes
outstanding will be precisely the same. Therefore the indirect
contraction so much dwelt upon will scarcely be felt. The volume of
greenbacks will be ample for the reserves of the banks, and their
growing scarcity will cause them to become more and more
valuable; and as they approach the standard of gold, so will they
sustain with golden support the bank-notes into which they are
convertible.
The demand by the people for legal-tender will not be appreciably
increased, as the bank-note is receivable by the Government for all
dues except customs, and those demands are necessarily localized.
While the growing scarcity of greenbacks, because of their
replacement by bank-notes fulfilling all the requirements of general
trade, will not be noticed by the people, the banks will take heed lest
they fall, and at an early day begin to strengthen themselves. Legal-
tender reserves they must have, and, with the honest eyes of our
Secretary of the Treasury to detect any deficiency, they will begin
their strengthening policy at once. Instead of putting gold received
as interest forthwith on the market for sale, they will put it snugly
away in their vaults. The gold which comes to them in the course of
banking operations will be added thereto; and almost imperceptibly
the country banks will arrive at the condition of the city banks,
whose reserves in coin and legal-tender notes are now far beyond
the requirements of law. In the mean time, and without
derangement of business, the Treasury may strengthen its reserve,—
while, on the other hand, the quiet reduction of its liabilities
advances the percentage of the reserve to the whole amount of
liabilities in almost a compound ratio. With this strengthening of the
condition of the Treasury, made manifest to all the world by its
monthly publications, the mistrust of the people will be gradually,
but surely, dissipated, and as surely be replaced by confidence that
all demand obligations will be redeemed at an early day,—a
confidence as wide-spread and deep-seated as is that now prevailing
in relation to our bonded debt, that it will be paid according to the
spirit as well as the letter of the law.
It will thus be seen that just in proportion to the strengthening of
the legal-tender do we strengthen the bank-note. Strike out of
existence in a single day the legal-tender notes, and I fear that the
bank-note would for a time fall in comparative value: so would
everything else. But I advocate no such violent measure.
The Senator from Indiana in his remarks appeared to forget that
we have in the country two or three hundred millions of another
legal-tender,—being coin, now displaced, of which no legitimate use
is made in connection with the currency,—that should resume its
proper position in the paper circulation of the country. Here are two
or three hundred millions of money, now by force of law
demonetized, which I would have relieved of its disabilities. I would
change the relation of master it now occupies to that of servant,
where it properly belongs; and I would inflate the currency with it to
the extent that we possess it. Inflation by coin is simply specie
payment, or very near it.
I have endeavored, Mr. President, thus briefly to respond to the
questions propounded to me. I do not know that I have entered
sufficiently into detail to explain clearly my convictions as to the
necessity for reducing the volume of legal-tender obligations, and to
prove, as I desire to prove, that their gradual withdrawal will
enhance not only the value of the remainder, but also the value of
the bank-note. Both will ascend in the scale. This enhancement of
the whole paper currency will tend to draw the coin of the country
from its seclusion. As in the early period of the war, before the
present currency was created, we were astonished at the positive,
but hidden, money resources of the people, so will the outflow of
hidden coin confound the calculations of those who suppose that its
volume is to be measured by the amount in the Treasury and in the
New York banks.
Mr. President, I am not alone in asking for the reformation of our
currency as the first stage of our financial efforts. I read from the
“Commercial and Financial Chronicle”[221]
of New York, an
authoritative paper on this subject, as follows:—
“In any practical scheme to improve the Government
finances and credit, or to restore prosperous activities,
or both at once, the first thing to be done must be the
restoration of a sound currency. That done or provided
for, all the rest will be easy; the best credit and the
lowest rates of interest will follow.”
To this end our greenbacks must be absorbed or paid, and my
proposition provides a way. As the greenbacks are withdrawn, coin
will reappear to take their place in the banks and the business of the
country. This will be specie payments.
Here I wish to remark that I fail to see the asserted dependence
of our demand notes on our bonds. The bonds may be at par
without bringing the notes to par, and so the notes may be at par
without bringing the bonds to par. According to the experience of
other countries, bonds and notes do not materially affect each other.
The two travel on parallel lines without touching. Each must be
provided for; and my present purpose is to provide for the demand
notes.
There is strong reason why this is the very moment for this effort.
According to statistical tables now before me, our exports are
tending to an equality with our imports. During the five months of
July, August, September, October, and November, 1869, there has
been a nominal balance in our favor of $1,752,416; whereas during
the same months of last year there was an adverse balance of
$32,163,339. The movement of specie is equally advantageous.
During the five months above mentioned there has been an import
in specie of $10,056,316 against $5,273,116 during the same
months last year, and an export in specie of $19,031,875 against
$21,599,758 during the same months last year.[222]
According to
these indubitable figures, the tide of specie as well as of business is
beginning to turn. It remains for us by wise legislation to take
advantage of the propitious moment. Take the proper steps and you
will have specie payments,—having which, all the rest will follow.
Because I desire to secure this great boon for my country I now
make this effort.
The amendment was rejected.
March 2d, Mr. Sumner’s bill having been reported back from the Committee on
Finance with an amendment in the nature of a substitute, he spoke in review of
their respective provisions as follows:—
Mr. President,—The measure now before the Senate concerns
interests vast in amount and influence. I doubt if ever before any
nation has attempted to deal at once with so large a mass of
financial obligations, being nothing less than the whole national debt
of the United States. But beyond the proper disposition of this mass
is the question of taxation, and also of the extent to which the
payment of the national debt shall be assumed by the present
generation, and beyond all is the question of specie payments. On
all these heads my own conclusions are fixed. The mass of financial
obligations should be promptly adjusted in some new form at
smaller interest; taxes must be reduced; the payment of the national
debt must be left in part to posterity; specie payments must be
provided for.
The immediate question before the Senate is on a substitute
reported by the Committee for the bill which I had the honor of
introducing some weeks ago. Considering my connection with this
measure, I hope that I shall not intrude too much, if I recur to the
original bill and explain its provisions.
There are certain general objects which must not be forgotten in
our present endeavor. I have already said that the taxes must be
reduced. Here I am happy to observe that the popular branch of
Congress, in the exercise of its constitutional prerogative, has taken
the initiative and is perfecting measures to this end. I trust that they
will proceed prudently, but boldly.
In harmony with this effort the expenditures of the Government
should be revised and cut down to the lowest point consistent with
efficiency. Economy will be an important ally. Even in small affairs it
will be the witness to our purposes. Through these agencies our
currency will be improved, and we shall be brought to specie
payments, while the national credit will be established. Not at once
can all this be accomplished, but I am sure that we may now do
much.
As often as I return to this subject I am impressed by the damage
the country has already suffered through menacing propositions
affecting the national credit. I cannot doubt that in this way the
national burdens have been sensibly increased. By counter-
propositions in the name of Congress we have attempted to
counteract these injurious influences. We have met words with
words. But this is not enough.
There is another remark which I wish to make, although I do little
more than repeat what I said on another occasion.[223]
It is that a
national debt, when once funded, does not seem to affect largely
the condition of the currency. The value of the former is maintained
or depressed by circumstances independent of the currency. But, on
the other hand, the condition of the currency bears directly upon all
efforts for increased loans; and this is of practical importance on the
present occasion. The rules of business are the same for the nation
as for an individual; nor can a nation, when it becomes a borrower,
hope to escape the scrutiny which is applied to an individual under
similar circumstances. Applying this scrutiny to our case, it appears
that on our existing bonded debt we have thus far performed all
existing obligations,—not without discussion, I regret to add, that
has left in some quarters a lingering doubt with regard to the future,
and not without an opposition still alive, if not formidable. But the
case is worse with regard to that other branch of the national debt
known as legal-tenders, where we daily fail to perform existing
obligations, so that these notes are nothing more than so much
failed paper. With regard to this branch of the national debt there is
an open confession of insolvency, and each day renews the
confession. Now, by the immutable laws of credit, which all
legislative enactments are impotent to counteract or expunge, the
nation must suffer when it enters the market as a borrower. Failing
to pay these obligations already due, it must pay more for what it
borrows. Nor can we hope for more than partial success, until this
dishonor is removed.
With these preliminary remarks, which are rather hints than
arguments, I come directly to the measure before the Senate; and
here I begin with the first section.
I wish the Senate would note the difference between this section
in my bill and in the substitute of the Committee. I proposed to
authorize the issue of $500,000,000 of Ten-Forty five per cents., and
prescribe the use to which the proceeds of such bonds should be
applied. The Committee propose $400,000,000 of Ten-Twenty five
per cents., and leave the application of the proceeds the subject of
discretion. Between the two propositions there are several
differences: first, in the amount; secondly, in the length of the bond;
and, thirdly, in the application of the proceeds.
Here I beg to observe that the original sum of $500,000,000 was
not inserted by accident, or because it was a round and euphonious
sum. Nothing of the kind. It was the result of a careful examination
of the national debt in its details, especially in the light of the
national credit. It was adopted because it was the very sum required
by the nature of the case. At least so it seemed to me. A brief
explanation will show if I was not right.
The year 1862, which marks the date of our legal-tenders, marks
also the date of a new system in regard to our loans. Senators are
hardly aware of this change. Previously our standard for sixes was
an immutable loan for twenty years. By the new system this
immutability was continued as to the right of demand by the
bondholder, but the right of payment was reserved to the nation at
any time after five years. This change, as we now see, gave positive
advantages to the nation. Its disadvantages to the bondholder were
so apparent that it encountered resistance, which was overcome
only after undaunted perseverance and final appeal to the people.
Now, by recurring to the schedule of the national debt, you will find
that the first loan within the sphere of this discretionary system is
the Five-Twenties of 1862, which, on the 1st of February last, after
deducting the purchased bonds, were $500,000,000. This, therefore,
is the first loan falling within our discretion, the first loan we are
privileged to pay before maturity, and the first loan presenting itself
for payment. In these incidents the loan of 1862 has precedence,—it
stands first.
But there is a reason, which to my mind is of peculiar force, why
this first loan should be paid in coin at the earliest possible day. It
seems to me that I do not deceive myself, when I consider it
conclusive on this question. The loan of 1862 is the specific loan
which has been made the objective point of all the movements
under the banner of Repudiation. It is the loan to which this idea
first attached itself. It is the loan first menaced. Therefore, to my
mind, it is the loan which should be first provided for. I know no way,
short of universal specie payments, by which the national credit can
be so effectually advanced.
Why in the amendment of the Committee the amount of the
proposed issue is placed at $400,000,000 I am at a loss to conceive.
Here is no equivalent of any one loan, nor of two or more loans. It is
an accidental sum, and might have been more or less for the same
reason that it is what it is. The term Ten-Twenties seems also
accidental, as it is unquestionably new. Of course it is assumed that
the amount proposed of Ten-Twenties at five per cent. will absorb an
equal amount of Five-Twenties at six per cent., irrespective of any
particular loan; but I am at a loss to see on what grounds the
holders of the sixes can be induced to make the exchange. Will the
substitute bonds be considered of equal value? I affirm not. But
assuming that they are acceptable, how shall they be acceptably
distributed? Shall the first comer be first served? If all were at the
same starting-point, the palm might be justly bestowed upon the
most swift. In the latitude allowed, stretching over all the Five-
Twenties, there would be opportunity for favoritism; and with this
opportunity there would be temptation and suspicion.
The change from a Ten-Forty bond to a Ten-Twenty bond, as
proposed by the Committee, is a change, so far as I can perceive,
made up of disadvantages. To the nation there is the same rate of
interest, and there is the same fixed period during which this interest
must be paid; while, on the other hand, the period of optional
payment is reduced from thirty years to ten years. If there be
advantage in this reduction, I do not perceive it. If at the expiration
of ten years we are in a condition to pay, we may do so as readily
under a Ten-Forty as under the Ten-Twenty proposed. If during the
subsequent ten years of option our advancing credit enables us to
command a lower rate of interest, surely we may do so just as
favorably under one as under the other. There is no benefit within
the bounds of imagination, so far at least as I can discern, which will
not redound to the nation from Ten-Forties as much as from Ten-
Twenties. On the other hand, it is within possibilities, from
disturbance in the money markets of the world, or from other
unforeseen circumstances, that it may not be convenient during the
short optional period of the Committee to obtain the necessary coin
without a sacrifice. The greater latitude of payment leaves the
nation master of the situation, to pay or not to pay, as is most for
the national advantage.
Furthermore, the loan proposed by the Committee has not, to my
mind, the elements of success promised by the other loan. It is
assumed in both cases that the coin for the redemption of the
existing obligations shall be obtained in Europe. Then we must look
to the European market in determining the form of the new loan.
Now I have reason to believe that a coin loan to the amount of
$500,000,000 may be obtained in Europe on Ten-Forties at par,
provided the new bonds are of the same form and purport as the
Ten-Forties which are already so popular, and provided further that
the proceeds of the loan are applied to the payment in coin at par of
the Five-Twenties of 1862. The reasons are obvious. The Ten-Forties
have a good name, which is much to start with. It is like the credit
or good-will of an established mercantile house, which stands often
instead of capital; and then the fact that the proceeds are to be
absorbed in the redemption of the first Five-Twenties, so often
assailed, will most signally attest the determination of the country to
maintain its credit. These advantages cost nothing, and it is difficult
to see why they should be renounced.
We must not make an effort and fail. Our course must be guided
by such prudence that success will be at least reasonably certain.
For the nation to offer a loan and be refused in the market will not
do. Here, as elsewhere, we must organize victory. Now it is to my
mind doubtful, according to the information within my reach, if the
loan proposed by the Committee can be negotiated successfully at
par. Bankers there may be who would gladly see themselves
announced as financial agents of the great Republic; but it remains
to be seen if there are any competent to handle a loan of
$500,000,000 who would undertake it on the terms of the
Committee. I am clear that it is not prudent to make the experiment,
when it is easy to offer another loan with positive advantages
sufficient to turn the scale. Washington, in his Farewell Address,
said, “Why forego the advantages of so peculiar a situation? Why
quit our own to stand upon foreign ground?” In the same spirit I
would say, Why forego the advantages of a well-known and peculiar
security? Why quit our Ten-Forties to stand upon a security which is
unknown, and practically foreign, whether at home or abroad?
In the loan proposed by the original bill we find assurance of
success, with the promise of reduced taxation, Repudiation silenced,
and the coin reserves in the banks strengthened by sales in Europe,
it may be, $150,000,000. Should the amendment of the Committee
prevail, I see small chance of any near accomplishment of these
objects, and meanwhile our financial question is handed over to
prolonged uncertainty.
I pass now to the substitute of the Committee for the second and
third sections of the original bill. Here again the amount is changed
from $500,000,000 to $400,000,000. I am not aware of any reason
for this change; nor is there, indeed, any peculiar reason, as in the
case of the Five-Twenties of 1862, for the amount of $500,000,000.
The question between the two amounts may properly be determined
by considerations of expediency, among which will be that of
uniformity with outstanding loans. A more important change is in the
time the bonds are to run, which is Fifteen-Thirty years for the bonds
at four and a half per cent., and Twenty-Forty years for the bonds at
four per cent. Here occurs again the argument with regard to the
inferiority of Ten-Twenties, as compared with Ten-Forties. By the
same reason the Fifteen-Thirties will be inferior to the Fifteen-Fifties,
and the Twenty-Forties will be inferior to the Twenty-Sixties, of the
original bill.
The prolongation of the bond is in the nature of compensation for
the reduction of interest. Already we have established the ratio of
compensation for such reduction,—already for a loan at six per cent.
we have offered Five-Twenties, but for a loan at five per cent. we
have offered Ten-Forties,—and I see no reason why by a tentative
process we should so materially change this standard as is now
proposed. The experiment can do no good, while it may do harm. It
is in the nature of a restriction on our discretion, and a limitation of
the duration of the bond, which, I apprehend, must interfere
essentially with its marketable character. While the prolongation of
time enlarges the option of the nation, it increases the value of the
bond in the market. That which is most favorable to the nation is
most favorable to the market value of the bond; and that which is
unfavorable to the nation is unfavorable also to the market value of
the bond, rendering its negotiation and sale more difficult and
protracted. Thus at every turn are we brought back to the original
proposition.
Against this conclusion is the argument founded on the idea of
English consols. It is sometimes said, If the short term of Five-
Twenty years is the standard for a six per cent. bond with a
graduation to Twenty-Sixty for a four per cent. bond, why may we
not go further, and establish consols at three per cent., running, if
you please, to eternity?—The technical term “consols” is an
abbreviation for the consolidated debt of Great Britain, and in the
eyes of a British subject has its own signification. It means a debt
never to be paid, or at least it is an inscribed debt carrying no
promise of payment. I would not have any debt of the United States
assume either the form or name of consols. I would rigidly adhere to
definite periods of payment. This is the American system, in
contradistinction to the British system. I would not only avoid the
idea that our debt is permanent, but I would adhere to the form of
positive payment at some fixed period, and keep this idea always
present in the minds of the people. Without the requirement of law,
I doubt if the debt would be paid. Political parties would court
popularity by a reduction of taxation. The Treasury of the United
States, like the British Treasury, would always be without a surplus,
and the national debt would be recognized as a burden to be
endured forever. Therefore do I say, No consols.
There is another consideration, having a wide influence, but
especially important at the West and South, which should induce us
to press for a reduction of the interest on our bonds; and here I
present an argument which, if not advanced before, is none the less
applicable.
Do Senators consider to what extent the Government determines
the rates of interest in the money centres of the country? Not only
for itself does it determine, but for others also. Government bonds
enjoy preëminence as an investment,—and if the interest is high,
they attract the disposable money of the country. Government sixes
are worth more than a six per cent. bond of any private corporation
or individual, no matter how well secured. Therefore, it is easy to
see, so long as we retain our standard at six per cent., so long as we
have sixes, will the capital of the country seek these bonds for
investment, permanent or temporary, to the detriment of numerous
enterprises important to the national development, which are driven
to be the stipendiaries of foreign capital. Railroads, especially at the
West and South, are sufferers, being sometimes delayed by the
difficulty of borrowing money, and sometimes becoming bankrupt
from ruinous rates of interest, always in competition with the
Government. But what is true of railroads is also true of other
enterprises, which are pinched, and even killed, by these exactions
in which the Government plays such a part. All are familiar with the
recurring appeals for money on bonds even at eight per cent., which
is more than can be paid permanently without loss; and even at
such a ruinous rate there is difficulty in obtaining the required
amount.
Doubtless the excessive interest now demanded is partly due to
our fictitious currency, where failed paper is forced upon the market;
but beyond this influence is that of our sixes, absorbing disposable
capital. I venture to assert, that, if we could at an early day reduce
these sixes to fives, there are millions which would be released to
seek investment in other securities at six per cent., especially to the
relief of the West and South. The reduction of interest to four and a
half per cent. and four per cent. would release further millions. A
recent incident in the financial history of Massachusetts illustrates
the disturbing influence of our sixes. An attempt to obtain a loan in
Europe at five per cent. was unsuccessful, chiefly because the
National Government offered six per cent.
Therefore, for the sake of public enterprise in its manifold forms,
for the sake of that prosperity which depends on human industry, for
the sake of manufactures, for the sake of commerce, and especially
for the sake of railroads, by which all these are quickened, we must
do what we can to reduce the general rate of interest, which is now
such a curb on enterprise; and here we must begin with our own
bonds. Without any adverse intention, the National Government is a
victorious competitor, and the defeated parties are those very
enterprises whose success is so important to the country. A
competition so destructive should cease. Keeping this before us in
the new loan, we shall adopt that form of bond by which the interest
will most surely be reduced. Thus, while refunding the national debt,
we shall open the way to improvements of all kinds.
This is what I have to say for the present on the refunding
propositions of the Committee. Their object is the same as mine. If I
differ from them in details, it is because after careful consideration it
seems to me that in some particulars their system may be improved.
Proceeding from these pivotal propositions, I find other things
where I must again differ. When I first addressed the Senate on this
subject, I took occasion to declare my objection to the idea of
agencies or offices in the commercial centres of Europe, where
interest should be paid. I am not ready to withdraw that objection,—
though, if I could be tempted, it would be by the Senator from Ohio
[Mr. Sherman], when he held up the prospect of a common money
among nations. This is one of the desires of my heart, as it is one of
the necessities of civilization; but I fail to see how this aspiration will
be promoted by the system proposed,—which must be judged on its
own merits, without any such recommendation. It is easy to see that
such a system, besides being the beginning of a new policy on the
part of the Government, may entail serious embarrassments. Sub-
treasuries must be created in foreign capitals, which must be
continued so long as the bonds last. Remittances of coin must be
semiannual; and should such remittances fail at any time, there
must be advances at no little cost to the Government. I cannot
imagine any advantage from this new system sufficient to induce us
to encounter the possible embarrassments or entanglements which
it may cause.
I would not take too much of the time of the Senate, and
therefore I pass at once to the proposition of the Committee, being
section seven, providing for the very early payment of the national
debt.
Mr. President, the payment of the national debt is an American
idea, and I would say nothing to weaken it among the people.
Whatever we owe must be paid; but it is the part of prudence to
make the payment in such way as, while consistent with our
obligations, shall promote the national prosperity. In this spirit I
approach the proposition of the Committee, in which there is so
much of good, only to examine and measure it, in order to ascertain
its probable influence, especially on the question of Taxation.
Here it must be borne in mind, that the present measure in all its
parts, so far as applicable, and especially with its guaranties and
pledges, must be taken as the basis of our new engagements. The
provision that so much of the debt shall be paid annually will
become in a certain sense a part of the contract, although not so
expressed in the bond. Not less than $150,000,000 are set apart
annually to be applied “to the payment of the interest and to the
reduction of the principal of the public debt.” This is a large sum,
and we should consider carefully if such a guaranty or pledge has in
it the promise of financial stability. Promising too much is sometimes
as bad as promising too little. Our promise must be according to our
means prudently employed.
If we assume obligations so large as to bear heavily upon the
business of the country and to compel unreasonable taxation, there
will be little chance of financial stability. They will become the object
of attack, and will enter into the conflict of parties,—and if repealed,
the national faith may be called in question. I need not say that
business must suffer. A less ambitious effort on our part will be less
obnoxious to attack,—thus leaving the bonds to their natural position
in the money market, and strengthening all the movements of
commerce.
In order to determine the operation of this provision we must look
into details. I have the estimates before me, showing our present
and prospective liabilities for interest; but I content myself with
presenting compendiously the result, in order to determine the
question of taxation. Suffice it to say, that under the operation of the
present measure there will be in 1871, after the payment of all
liabilities for interest, a surplus of $43,000,000 to be applied to the
payment of the national debt. With each succeeding year the
reduction of interest will rapidly increase this surplus; and when we
bring into operation other provisions of the bill, and convert
$500,000,000 of sixes into a like amount of four and a half per
cents., effecting a further saving of interest, equal to $7,500,000
annually, the surplus revenue, as compared with necessary
expenditures, will in a brief period approach $100,000,000 annually.
Here the question arises, Is not this unnecessarily large? Is it not
beyond the bounds of prudence and wise economy? Shall we declare
in this fundamental measure a determination to redeem the whole
national debt within a period of twenty-five years? Can the industries
of the country sustain such taxation? I put the question. You shall
answer it. The future has its great claims upon us; so also has the
present. I submit that the pending measure sacrifices the present. I
conclude, therefore, as I began, with another appeal for reduced
taxation. At the proper time I shall move an amendment, in order to
aid this result.
In the course of the proceedings which followed, the bill of the Committee
underwent important amendments, in accordance with the views expressed by Mr.
Sumner,—for the Ten-Twenties and Fifteen-Thirties therein proposed, a
prolongation to Ten-Forties and Fifteen-Forties being effected,—and the provision
for the payment of interest at the money-centres and in the moneys of Europe
stricken out. Some of its more objectionable features being thus removed, he gave
it a qualified support.
March 10th, the question being on striking out a provision in the bill of the
Committee requiring the national banks to exchange the bonds of the United
States deposited by them as security for their circulation for those bearing a lower
rate of interest, Mr. Sumner said:—
Mr. President,—There is a word which has been introduced into
this debate with which we were all very familiar in another relation
some years ago. It is the word Coercion. A President of the United
States announced in most formal phrase that we could not coerce a
State; and now, borrowing a phrase from Mr. Buchanan, we are told
we cannot coerce a national bank. Well, Sir, is the phrase applicable?
If it be applicable, then I insist that we can coerce a national bank;
but I do not admit its applicability. What I insist on has already been
so ably and clearly stated by the Chairman of the Committee [Mr.
Sherman] that perhaps I need not add another word. I do not like to
occupy your time; yet I cannot forbear reminding you, Sir, of the
plenary power which Congress has reserved over the banking
system in that very Act by which it was established.[224]
The Senator from California [Mr. Casserly] has read to you the
clause. We have been reminded to-day by a Senator on this floor
that these are formal words, words that often appear in statutes. But
are they not significant words? Have they not a meaning? Why are
they there? Because they have a meaning; because they reserve to
Congress what I call plenary power over the whole system. That
system may be readjusted, modified, shaped anew, and the banks
cannot complain. They began their existence under that law; they
knew the conditions of their being; and they cannot now murmur, if
Congress chooses to exercise the prerogative which it reserved at
the very inception of the whole system.
Sir, I approach this question, therefore, with the conviction that
the whole matter is open to our discretion. Nobody can say safely
that what is now proposed is not within the power of Congress.
Congress may do it, if the occasion justifies, if in its discretion it
thinks best to do it. It may do it, if it thinks that the financial policy
of this country will be thereby promoted. The banks are all parties to
that policy. May not the country turn around and ask the banks to do
their part in this great work of renovation? To a certain extent the
banks are in partnership with the Government. May not the
Government insist that they shall do their part on this great
occasion? Shall this effort of ours to readjust our finances and to
save this large interest to our country be thwarted by a pretension
on the part of the banks that we have not the power to interfere?
But we are reminded that there is a difference between power and
right. How often, Sir, on other occasions, have I so insisted in this
Chamber! A great, broad, vital distinction there always is between
power and right. A nation or an individual may have a power without
right. Now is there not here a right as well as a power? I cannot
doubt it. I cannot doubt that Congress may rightfully exercise what I
cannot doubt is an existing power. Why should it not? It could
exercise it—who can doubt?—with reference to the public interests,
to promote the national credit. It will not exercise it in any spirit of
wantonness, in any spirit of injustice,—but to promote the national
credit. Is not that a rightful object? No one will say the contrary.
Why, then, shall we hesitate?
We are reminded that these banks have secured certain privileges,
and it is said often that those are vested, and the old phrase “vested
rights” has been repeated. But how can they have vested rights
under a statute which contains the provision just read to us,
securing to Congress full power to change it in every respect? What,
then, is the simple aspect of this question? It is that certain
securities have been lodged with the Government by these banks on
which they transact their business, and now in readjusting the
national debt it is deemed advisable and for the public interests that
the securities should be at a lower rate of interest than when they
were originally deposited. Is it not right for Congress to require that?
I cannot see the wrong in it. I cannot see any doubt on the
question. To my mind it is clear; it is absolutely within the province
of Congress, in the exercise of the discretion which it originally
retained over this whole subject.
I hope, therefore, that in this debate we shall not be pressed too
much with the suggestion that we cannot coerce these banks. If the
occasion requires, and if the term be applicable, then do I say we
may coerce these banks to the extent of obliging them to take these
securities at a reduced rate of interest. I find no Repudiation in that.
I find nothing wrong in that. I find nothing in it but a simple
measure in harmony with this great process of Financial
Reconstruction in which we are now engaged. I call it Financial
Reconstruction; and in this work ought not the banks to take their
place and perform their part?
Now, Sir, I have a criticism on this section. It does not go far
enough. The Committee propose that the banks shall take one third
of the three different kinds of bonds, the five, the four and a half,
and the four per cents. I think they ought to be required to take all
in fours, and I propose to give the Senate an opportunity of
expressing its judgment on that proposition. I may be voted down;
perhaps I shall be; but I shall make a motion, in the honest
endeavor to render this bill a practical measure, which can best
succeed. I wish to mature it; I wish to put it in the best shape
possible; and for the sake of the banks, and in the interest of the
banks, I wish such a measure as shall have a reasonable chance of
stability in the future. If you allow the banks gains that are too large,
there will necessarily be a constant opposition, growing and
developing as their gains become more conspicuous. Why expose
the system to any such criticism? Let us now revise it carefully, place
it on sure, but moderate foundations, so that it will have in itself the
elements of future stability.
To my mind that is the more politic course, and I am sure it is not
unjust. You and I, Mr. President, remember very well what was done
on another occasion. The State banks were taxed out of existence. It
was the cry, “Tax them out of existence! do not let them live! drive
them from competition with these new children of ours, the national
banks!” It was done. Was not that coercion? If the phrase is to be
employed, there was an occasion for it. But I am not aware that it
was argued, certainly it was with no great confidence argued, that to
do that was unjust. It was a measure of policy wisely adopted at the
time, and which we all now see has answered well. But if we could
tax the State banks out of existence, can we not, under the very
specific terms of the Act of Congress to which these national banks
owe their existence, apply a rule not unlike to them? We do not
propose to tax them out of existence, but we propose to require that
they shall lodge with the Government securities at a lower rate of
interest.
Something has been said, perhaps much, in this debate, with
regard to the burden that this will impose upon the banks. The
Senator from Ohio [Mr. Sherman] has already answered that
objection, and I do not know that I can add to his answer; and yet I
am not aware that he reminded the Senate that in this very bill there
is a new and important provision in favor of the banks, or in favor of
all bondholders,—being an exemption from all taxation, not only
State and municipal, but national.
There is but one other remark I will make, and that is, we all
know, unless I am much deceived, that the banks have during these
last years made great profits. I am told that the profits of the
national banks are two or three times greater than those of the old
State banks, which we did not hesitate to tax out of existence. Now
is not that a fact in this case? Is it not an essential element? Should
it not be taken into consideration on this occasion? If these national
banks are the recipients of such large profits, should we not exercise
all the power that belongs to us to compel them to their full
contribution to this great measure of Financial Reconstruction? I
cannot hesitate in my conclusion.
March 11th, Mr. Sumner moved the addition of a section providing for the
resumption of specie payments,—being the seventh section of the original bill,—
remarking:—
Mr. President,—Interested as I am in this bill, desirous of its
passage hardly less than the Senator from Ohio, I am bound to say,
that, in my judgment, the passage of this single section would be
worth more than the whole bill. It would do more for the credit of
the country; it would do more for its business. It would help us all to
the completion of Financial Reconstruction. How often have I
insisted that all our efforts to fund and refund are to a certain extent
vain and impotent, unless we begin by specie payments! That, Sir, is
the Alpha of this whole subject; and until Congress is ready to begin
with that, I fear that all the rest will be of little avail. It is in the light
of expedient rather than of remedy. There is the remedy.
The proposition was negatived,—Congress not being yet ready for this step.
M
MAJOR-GENERAL NATHANAEL
GREENE, OF THE REVOLUTION.
Speech in the Senate, on the Presentation of his Statue, January 20,
1870.
In the Senate, January 20, 1870, Senator Anthony announced the presentation
by Rhode Island of a statue of Major-General Nathanael Greene, of the Revolution,
executed by the sculptor Brown, to be placed in the old Hall of the House of
Representatives. Mr. Sumner moved its acceptance by the following Concurrent
Resolution:—
A Resolution accepting the Statue of Major-General Greene.
Resolved by the Senate, the House of Representatives
concurring, That the thanks of this Congress be presented to the
Governor, and through him to the people, of the State of Rhode
Island and Providence Plantations, for the statue of Major-General
Greene, whose name is so honorably identified with our
Revolutionary history; that this work of art is accepted in the
name of the nation, and assigned a place in the old Hall of the
House of Representatives, already set aside by Act of Congress
for the statues of eminent citizens; and that a copy of this
Resolution, signed by the President of the Senate and the Speaker
of the House of Representatives, be transmitted to the Governor
of the State of Rhode Island and Providence Plantations.
On this he spoke as follows:—
R. PRESIDENT,—How brief is life! how long is art! Nathanael
Greene died at the age of forty-four, and now Congress receives
his marble statue, destined to endure until this Capitol crumbles to
dust. But art lends its longevity only to lives extended by deeds.
Therefore is the present an attestation of the fame that has been
won.
Beyond his own deserts, Greene was fortunate during life in the
praise of Washington, who wrote of “the singular abilities which that
officer possesses,”[225]
—and then again fortunate after death in the
praise of Hamilton, whose remarkable tribute is no ordinary record.
[226]
He has been fortunate since in his biographer, whose work
promises to be classical in our literature.[227]
And now he is fortunate
again in a statue, which, while taking an honorable place in
American art, is the first to be received in our Pantheon. Such are
the honors of patriot service.
Among the generals of the Revolution Greene was next after
Washington. His campaign at the South showed military genius of no
common order. He saved the South. Had he lived to take part in the
National Government, his character and judgment must have
secured for him an eminent post of service. Unlike his two great
associates, Washington and Hamilton, his life was confined to war;
but the capacities he manifested in command gave assurance that
he would have excelled in civil life. His resources in the field would
have been the same in the council chamber.
Of Quaker extraction, Greene was originally a Quaker. The Quaker
became a soldier and commander of armies. Such was the
requirement of the epoch. Should a soldier and commander of
armies in our day accept ideas which enter into the life of the
Quaker, the change would only be in harmony with those principles
which must soon prevail, ordaining peace and good-will among men.
Looking at his statue, with military coat and with sword in hand, I
seem to see his early garb beneath. The Quaker general could never
have been other than the friend of peace.
Standing always in that beautiful Hall, the statue will be a
perpetual, though silent orator. The marble will speak; nor is it
difficult to divine the lesson it must teach. He lived for his country,
and his whole country,—nothing less. Born in the North, he died in
the South, which he had made his home. The grateful South
honored him as the North had already done. His life exhibits the
beauty and the reward of patriotism. How can his marble speak
except for country in all its parts and at all points of the compass? It
was for the whole country that he drew his sword of “ice-brook
temper.” So also for the whole country was the sword drawn in these
latter days. And yet there was a difference between the two
occasions easy to state.
Our country’s cause for which Greene contended was National
Independence. Our country’s cause recently triumphant in bloodiest
war was Liberty and Equality, the declared heritage of all mankind.
The first war was for separation from the mother country, according
to the terms of the Declaration, “That these United Colonies are and
of right ought to be Free and Independent States,”—the object being
elevated by the great principles announced. The second war was for
the establishment of these great principles, without which republican
government is a name and nothing more. But both were for country.
The larger masses, with the larger scale of military operations, in the
latter may eclipse the earlier; and it is impossible not to see that a
war for Liberty and Equality, making the promises of the Declaration
a reality, and giving to mankind an irresistible example, is loftier in
character than a war for separation. If hereafter Greene finds rivals
near his statue, they will be those who represented our country’s
cause in its later peril and its larger triumph. Just in proportion as
ideas are involved is conflict elevated, especially if those ideas
concern the Equal Rights of All.
Greene died at the South, and nobody knows the place of his
burial. He lies without epitaph or tombstone. To-day a grateful
country writes his epitaph and gives him a monument in the Capitol.
PERSONAL RECORD ON
RECONSTRUCTION WITH COLORED
SUFFRAGE.
Remarks in the Senate, January 21 and February 10, 1870.
The arraignment of Mr. Sumner by Mr. Trumbull, of Illinois, in the closing debate
on the Virginia Bill, January 21st, included, as remarked in that connection,[228]
a
reference to matters of earlier date,—specifically among these being the
Reconstruction Act of March 2, 1867, conferring upon the colored people of the
Rebel States equality of suffrage with the whites.[229]
Adverting to the fact that
this bill was an amendment in the nature of a substitute for one from the House,
and then reading the names of the Senators who voted for it, Mr. Trumbull asked,
—
“Mr. President, do you miss the name of any Senator from that
list of Yeas?—That was the vote by which that amendment was
adopted.—The ‘Absent’ were, among others, ‘Mr. Sumner.’”
And upon this showing, Mr. Trumbull concluded, that,
“Unfortunately the colored citizens of the South have nothing to
thank the Senator from Massachusetts for, in having the right of
suffrage conferred upon them.”
Mr. Trumbull continued:—
“Mr. President, this was not the only vote. A vote was taken,
after this amendment was adopted, upon the passage of the bill
thus amended; and the vote on the passage of the bill was Yeas
29, Nays 10, and among those Yeas is not found the name of the
Senator from Massachusetts.
“But, Sir, it sometimes happens that malice and hatred will
produce results which reason and good-will can never accomplish;
and when we passed this bill giving the right of suffrage to the
colored men in the South without the aid of the Senator from
T
Massachusetts and sent it to the President [Mr. Johnson] he
vetoed it, and on the question of passing it over his veto the
Senator from Massachusetts voted with us. His affection for the
President was not such as to allow him to coincide with him in
anything. So we got his vote at last, but we had two-thirds
without him.
“This is the record, Mr. President.”
Mr. Sumner answered:—
his assault to-day compels me to make a statement now which I
never supposed I should be called to make. I make it now with
hesitation, but rather to show the Senator’s course than my own. Sir,
I am the author of the provision in that Act conferring suffrage; and
when I brought it forward, the Senator from Illinois was one of my
opponents,—then as now. Senators who were here at that time
remember well that this whole subject was practically taken for the
time from the jurisdiction of the Senate into a caucus of the
Republican party, where a committee was created to whom all
pending measures of Reconstruction were referred. I had the honor
of being a member of that committee. So was the Senator from
Illinois. So was my friend from Michigan [Mr. Howard]. The Senator
from Ohio [Mr. Sherman] was our chairman. In that committee this
Reconstruction Bill was debated and matured sentence by sentence,
word for word; and then and there, in that committee, I moved that
we should require the suffrage of all persons, without distinction of
color, in the organization of new governments, and in all the
constitutions to be made.
In making this proposition at that time I only followed the
proposition I had made in the Senate two years before,[230]
which I
had urged upon the people in an elaborate address at a political
convention in Massachusetts,[231]
which I had again upheld in an
elaborate effort for two days in this Chamber,[232]
and which from the
beginning I had never lost from my mind or heart. It was natural
that I should press it in committee; but I was overruled,—the
Senator opposing me with his accustomed determination. I was
voted down. The chairman observed my discontent and said, “You
can renew your motion in caucus.” I did so, stating that I had been
voted down in committee, but that I appealed from the committee to
the caucus. My colleague [Mr. Wilson], who sits before me, called
out, “Do so”; and then rising, said, in language which he will pardon
me for quoting, but which will do him honor always, “The report of
the committee will leave a great question open to debate on every
square mile of the South. We must close that question up.” Another
Senator, who is not now here,—I can therefore name him,—Mr. Gratz
Brown [of Missouri], cried out most earnestly, “Push it to a vote; we
will stand by you.” I needed no such encouragement, for my
determination was fixed. There sat the Senator from Illinois, sullen
in his accustomed opposition. I pushed it to a vote, and it was
carried by only two majority, Senators rising to be counted. My
colleague, in his joy on the occasion, exclaimed, “This is the greatest
vote that has been taken on this continent!” He felt, I felt, we all
felt, that the question of the suffrage was then and there secured.
By that vote the committee was directed to make it a part of
Reconstruction. This was done, and the measure thus amended was
reported by the Senator from Ohio as chairman of the committee.
I am compelled to this statement by the assault of the Senator. I
had no disposition to make it. I do not claim anything for myself. I
did nothing but my duty. Had I done less, I should have been
faithless,—I should have been where the Senator from Illinois placed
himself.
The Senator read from the “Globe” the vote on the passage of the
bill, and exulted because my name was not there. Sir, is there any
Senator in this Chamber whose name will be found oftener on the
yeas and nays than my own? Is there any Senator in this Chamber
who is away from his seat less than I am? There was a reason for
my absence on that occasion. I left this Chamber at midnight,
fatigued, not well, knowing that the great cause was assured,
notwithstanding the opposition of the Senator from Illinois,—
knowing that at last the right of the colored people to suffrage was
recognized. I had seen it placed in the bill reported from the
committee. There it was on my motion, safe against the assaults of
the Senator from Illinois. Why should I, fatigued, and not well,
remain till morning to swell the large and ascertained majority which
it was destined to receive?[233]
I have no occasion to make up any
such record. You know my fidelity to this cause. You know if I am in
the habit of avoiding the responsibilities of my position. I cannot
disguise, also, that there was another influence on my mind.
Reconstruction, even with the suffrage, was defective. More was
needed. There should have been a system of public schools, greater
protection to the freedmen, and more security against the Rebels, all
of which I sought in vain to obtain in committee, and I found all
effort in the Senate foreclosed by our action in caucus. Pained by
this failure, and feeling that there was nothing more for me to do,
after midnight I withdrew. On the return of the Act to the Senate on
the veto of the President, I recorded my vote in its favor.
What Mr. Trumbull calls “the record” in this case, and which Mr. Sumner, in the
surprise of the occasion, seemingly accepts, according to the obvious import of the
term, as substantially the complete record, inspection of either the Congressional
Globe or the Senate Journal shows to be very far from complete. The vote
following the Presidential veto was by no means the only one in which Mr.
Sumner’s name appears: between this and the vote which would seem from the
representation to have next preceded, designated as “the vote on the passage of
the bill,” there intervened another, involving in an important degree the character
and fate of the whole measure.
The bill in its original form, as it came from the House, was purely, as indicated
by its title, “a bill to provide for the more efficient government of the
insurrectionary States,” dividing them into military districts and placing them under
military rule,—this being deemed the only effectual means of suppressing the
outrages continually perpetrated upon the loyalists of the South, black and white,
—its Reconstruction features, which included the provision for colored suffrage,
being engrafted upon it by the Senate, coupled with considerable modifications of
its military details. It was on the votes at this stage, February 16th, that Mr.
Sumner’s name was wanting.
On the return of the bill to the House for concurrence in these amendments, it
at once encountered on the Republican side severe animadversion, aptly
expressed in the remark,—“We sent to the Senate a proposition to meet the
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

Similar to Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward (20)

PPTX
python full stack course in hyderabad...
sowmyavibhin
 
PPTX
python full stack course in madhapur, hyderabad
neeraja0480
 
PDF
Python Django Intro V0.1
Udi Bauman
 
PPT
Django, What is it, Why is it cool?
Tom Brander
 
PPTX
Django Framework Interview Guide - Part 1
To Sum It Up
 
PPTX
Introduction to DJANGO, a creative framework
bunnybro2953
 
PDF
Why Django
Idan Gazit
 
PPTX
Django Frame Work
AkashChaudhary111
 
PDF
Introducing Django
zerok
 
PDF
Introduction to Python and Django
solutionstreet
 
PDF
DjangoSki 2010 Keynote
davidascher
 
PDF
Django For Beginners Converted William S Vincent
sarkingiio
 
PDF
Python & Django
Allan114858
 
PPTX
Advanced Web Technology using Django.pptx
smartguykrish11
 
PPTX
Introduction to django
Vlad Voskoboynik
 
ODP
Introduce Django
Chui-Wen Chiu
 
PPTX
Django course
Nagi Annapureddy
 
PDF
Advantages Of Using Django Framework To Build Scalable.pdf
Mindfire LLC
 
PPTX
Python Django Basics
RahilMemon5
 
PPTX
Django Framework Overview forNon-Python Developers
Rosario Renga
 
python full stack course in hyderabad...
sowmyavibhin
 
python full stack course in madhapur, hyderabad
neeraja0480
 
Python Django Intro V0.1
Udi Bauman
 
Django, What is it, Why is it cool?
Tom Brander
 
Django Framework Interview Guide - Part 1
To Sum It Up
 
Introduction to DJANGO, a creative framework
bunnybro2953
 
Why Django
Idan Gazit
 
Django Frame Work
AkashChaudhary111
 
Introducing Django
zerok
 
Introduction to Python and Django
solutionstreet
 
DjangoSki 2010 Keynote
davidascher
 
Django For Beginners Converted William S Vincent
sarkingiio
 
Python & Django
Allan114858
 
Advanced Web Technology using Django.pptx
smartguykrish11
 
Introduction to django
Vlad Voskoboynik
 
Introduce Django
Chui-Wen Chiu
 
Django course
Nagi Annapureddy
 
Advantages Of Using Django Framework To Build Scalable.pdf
Mindfire LLC
 
Python Django Basics
RahilMemon5
 
Django Framework Overview forNon-Python Developers
Rosario Renga
 

Recently uploaded (20)

PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
epi editorial commitee meeting presentation
MIPLM
 
Difference between write and update in odoo 18
Celine George
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Horarios de distribución de agua en julio
pegazohn1978
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
infertility, types,causes, impact, and management
Ritu480198
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Controller Request and Response in Odoo18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Ad

Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward

  • 1. Django Javascript Integration Ajax And Jquery 1st Edition Jonathan Hayward download https://ebookbell.com/product/django-javascript-integration-ajax- and-jquery-1st-edition-jonathan-hayward-49052714 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Django Javascript Integration Ajax And Jquery Jonathan Hayward https://ebookbell.com/product/django-javascript-integration-ajax-and- jquery-jonathan-hayward-4100096 Decoupled Django Understand And Build Decoupled Django Architectures For Javascript Frontends 1st Edition Valentino Gagliardi https://ebookbell.com/product/decoupled-django-understand-and-build- decoupled-django-architectures-for-javascript-frontends-1st-edition- valentino-gagliardi-33356238 Decoupled Django Understand And Build Decoupled Django Architectures For Javascript Frontends Valentino Gagliardi https://ebookbell.com/product/decoupled-django-understand-and-build- decoupled-django-architectures-for-javascript-frontends-valentino- gagliardi-47965604 Decoupled Django Understand And Build Decoupled Django Architectures For Javascript Frontends Valentino Gagliardi https://ebookbell.com/product/decoupled-django-understand-and-build- decoupled-django-architectures-for-javascript-frontends-valentino- gagliardi-47965602
  • 3. Django 4 By Example Build Powerful And Reliable Python Web Applications From Scratch 4th Antonio Mel https://ebookbell.com/product/django-4-by-example-build-powerful-and- reliable-python-web-applications-from-scratch-4th-antonio-mel-46085550 Django Standalone Apps Learn To Develop Reusable Django Libraries 1st Edition Ben Lopatin https://ebookbell.com/product/django-standalone-apps-learn-to-develop- reusable-django-libraries-1st-edition-ben-lopatin-50195676 Django The Easy Way A Stepbystep Guide On Building Django Websites 2nd Edition Samuli Natri https://ebookbell.com/product/django-the-easy-way-a-stepbystep-guide- on-building-django-websites-2nd-edition-samuli-natri-50200506 Django 10 Template Development Scott Newman https://ebookbell.com/product/django-10-template-development-scott- newman-50478114 Django In Action Meap V01 Chapters 1 To 5 Of 20 Christopher Trudeau https://ebookbell.com/product/django-in-action- meap-v01-chapters-1-to-5-of-20-christopher-trudeau-50864070
  • 6. Django JavaScript Integration: AJAX and jQuery Develop AJAX applications using Django and jQuery Jonathan Hayward BIRMINGHAM - MUMBAI
  • 7. Django JavaScript Integration: AJAX and jQuery Copyright © 2010 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: January 2011 Production Reference: 1291210 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849510-34-9 www.packtpub.com Cover Image by Vinayak Chittar ([email protected])
  • 8. Credits Author Jonathan Hayward Reviewers Jake Kronika Michael Szul Acquisition Editor Steven Wilding Development Editor Maitreya Bhakal Technical Editors Vanjeet D'souza Conrad Sardinha Indexers Hemangini Bari Monica Ajmera Mehta Editorial Team Leader Akshara Aware Project Team Leader Ashwin Shetty Project Coordinator Joel Goveya Proofreader Sandra Hopper Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat
  • 9. Foreword In this book, we will be exploring Django JavaScript integration and build an Ajax application using jQuery. We will build a Web 2.0 intranet employee directory, and we will aim for a solution that is Pythonic in more ways than one. Web development that is more "Pythonic" than just Python This book is intended to be a book about how to do web development in the spirit of Python++. The term "Python++" as we use it here is not the usual "Python is great," even if that may also be our opinion, but a more direct analogy to C++. When the effort was made to improve the C language, the basic kind of improvement attempted was to expand and broaden the core language. It is no accident that Stroustrup's The C++ Programming Language is far longer than Kernigan and Ritchie's The C Programming Language. The latter is a small book describing a small core language, while the former is a large book made large by the large core language it describes. The analogy intended by Python++ is somewhat loose here, and specifically does not include a large, or even a small, expansion of the core language. It is possible to tinker with the core language—easy_extend lets you extend Python to include a do-while loop (where the test condition is first evaluated at the end, not the beginning)—or add primitive syntax so you can do things like if remote_ip in 10.0.0.0:, but this is almost beside the point. The real possibilities for expanding Python do not need to radically expand the core language, or change the core language at all. Django (http://www.djangoproject. com/) is not a general purpose enhancement to Python: if you are automating system administration tasks, for instance, you very probably have no reason to use Django. But for a limited problem domain, namely certain kinds of web development, Django is more Pythonic than Python. Python's cgi module is good for some kinds of small and simple tasks, but if you are going to make a serious, large-scale web application with many standard functions, using Python core language + Python standard library + Django is a fundamentally more Pythonic approach than just Python core language + Python standard library alone.
  • 10. On StackOverflow, someone asked the question, "Have you considered using Django and found good reasons not to?" There were various answers, but the answer with the most "up" votes by far said, "I am an honest guy, and the client wanted to charge by the hour. There was no way Django was going to make me enough money." Django itself is not the limit to Python++. Pinax (http://pinaxproject.com/) is built on top of Django and offers a "more Django than Django" platform to build a social network. Satchmo (http://satchmoproject.com/) is also "more Django than Django" for another narrower focus: e-commerce webshops. And there are other platforms built on Django; it is time well spent to search the Python Package Index (http://pypi.python.org/pypi) for Django to see what is already available. In this text we will often use "Django" as a shorthand for either basic Django or any of the many good tools built on top of Django. Depending on what you are trying to do, it may be that the bulk of the Python work in Django is resolved surprisingly quickly: you can build and brand a Pinax social network by doing little more than overriding the CSS and adding images. This book will address the Python side and try to give a solid basis for programming Python for Django, working with the templates, and so on, but that problem can often be solved so cleanly that most of the work that remains is styling and Ajax. Django and its templating engine Before further exploring technical details, it would be worth taking a look at the opinions and philosophy behind the Django templating language, because an understandable approach of, "������ Oh, it's a general purpose programming language very slightly adapted for templating,������������������������������������������� " is a recipe for needless frustration and pain. The Django developers themselves acknowledge that their opinions in the templating language are one just opinion in an area where different people have different opinions, and you are welcome to disagree with them if you want. If you don't like the templating system that Django comes with, Django is designed to let you use another. But it is worth understanding what exactly the philosophy behind the templating language is; even if this is not the only philosophy one could use, it is carefully thought out.
  • 11. The Django templating language is intended to foster the separation of presentation and logic. In its design decisions, both large and small, the Django's templating engine is optimized primarily for designers to use for designing, rather than programmers to use for programming, and its limitations are almost as carefully chosen as the features it provides. Unlike ASP, JSP, and PHP, it is not a programming language interspersed with HTML. It provides enough power for presentation, is intended not to provide enough power to do serious programming work where it doesn't belong (in the Django opinion), and is simple enough that some non-programmers can pick it up in a day. For a programmer, the difficulty of learning the templating basics is comparable to the difficulty of simple HTML or SQL: it is simple, and a good bit easier to learn than wrapping your arms around a regular programming language. It is likely that there are a number of Django programmers out there who started by asking, "Why doesn't the templating language just let you mix Python and HTML?" and after playing with it, found themselves saying, "This isn't what I would have come up with myself, but I really, really like it." Additional benefits include it being fast (most of the work is done by a single regular expression call, and the founders talk about disabling caching because it couldn't keep up with the template rendering engine's speed), secure (it is designed so that it can be used by untrusted designers without allowing a malicious designer to execute arbitrary code), and versatile enough to generate whatever text format you want: plain text, HTML, XML, XHTML, JSON, JavaScript, CSV, ReStructuredText, and so on. We will be using it to generate web pages and JSON, but Django's templating language is a general-purpose text templating solution. What we will do in this book—building a Web 2.0 intranet employee photo directory Many books will teach you a new technology by walking through a sample project. This book is no different, but the sample project is not a toy: it is a walk through making a real, live Web 2.0 intranet employee photo directory that you can customize to your organization's needs. This is something that is both useful, and will give us a tour of the potential for developing Ajax applications using Django on the server side and jQuery on the client side. - Jonathan Hayward
  • 12. About the Author Jonathan Hayward as a child ranked 7th in a nationwide math contest, and later programmed a video game on his calculator. He holds master's degrees in bridging mathematics and computer science (UIUC), and philosophy and theology (Cambridge). Jonathan has lived in the U.S., Malaysia, France, and England, and has studied well over a dozen dialects and languages. He wears the hats of author, philosopher, theologian, artist, poet, wayfarer, philologist, inventor, and a skilled web developer who holds a deep interest in the human side of computing. He has a website showcasing his works at http://JonathansCorner.com and can be reached via e-mail at [email protected]. I would like to thank my parents, John and Linda, who love learning and taught me faith, my brothers, Matthew, Kirk and Joe, my parish, St. Innocent of Moscow, for a wealth of support. I would also like to thank the editorial team at Packt: Steven Wilding, who helped me come up with the book idea in the first place, Ved Prakash Jha, who helped see it to completion, and Joel Goyeva, who helped me with innumerable logistics along the way. And, of course, the reviewers Jake Kronika and Michael Szul, who offered an invaluable sharpening. The Django list, [email protected], is worth its weight in gold. I would like to thank Daniel Roseman, Alex Robbins, Dan Harris, Karen Tracey, Oleg Lokalma, Mark Linsey, Jeff Green, Elijah Rutschman, Brian Neal, Euan Goddard, Sævar Öfjörð, "Ringemup", Ben Atkin, Tom Evans, Sam Lai, and Preston Holmes. Authors have to leave somebody out who deserves to be mentioned; that's just part of the territory. But I would like to thank one person in particular: the reader. You're really the reason the book is here, and you've chosen to invest some money in a book and some time in fascinating technologies and let me help you along the way. Thank you so much.
  • 13. About the Reviewers Jake Kronika, a web designer and developer with over fifteen years of experience, brings to this book a strong background in frontend development with JavaScript and AJAX, as well as exposure to the Django framework. Having earned a Bachelors of Science degree in Computer Science from Illinois Wesleyan University in 2005, with a minor in Business Administration, Jake went on to become Senior User Interface (UI) Specialist for Imaginary Landscape, LLC, a small web development firm in Ravenswood, on the north side of Chicago. In this role, the foundations of his strengths in Cascading Style Sheets (CSS) and JavaScript (JS) were built, as well as extensive use of Python and the Django Framework. From there, Jake went on to work for the Sun-Times News Group, owner of the Chicago Sun-Times and numerous suburban newspapers in Chicagoland. It was in this role that he was initially exposed and rapidly became an expert with the jQuery framework for JS. Following an intermediate position as Technology Consultant with Objective Arts, Inc, Jake has worked as UI Prototyper for JP Morgan Chase since February 2010. Since 1999, he has also operated Gridline Design & Development, a sole proprietorship for web design, development, and administration. I would like to thank my wife, Veronica, for her ongoing support. She and my twin children Mykaela and Kaden provide all the joy I could want in this world.
  • 14. Michael Szul has designed and developed software applications for Fortune 500 companies, including AIG and Praxair, since 1998. Later, he served as a senior software engineer for the technology division of Performance Media Group, contributing to their fast growth and success, including placement on the Inc. 5000. Szul's expertise in social software development led to a lateral move within the company to become the director of development for their travel social network. He even built successful social software for companies such as Apple Vacations and Conde Naste's Gourmet Magazine. As a partner at Barbella Digital, Inc., he currently designs and develops enterprise- level workflow systems and mobile applications for educational institutions.
  • 15. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. 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. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via 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 nine entirely free books. Simply use your login credentials for immediate access. • • •
  • 16. Table of Contents Preface 1 Chapter 1: jQuery and Ajax Integration in Django 7 Ajax and the XMLHttpRequest object 8 Human speech: An overlaid function 8 Ajax: Another overlaid function 8 The technologies Ajax is overlaid on 9 JavaScript 9 XMLHttpRequest 14 Methods 14 Properties 15 HTML/XHTML 17 XML 18 JSON 18 CSS 19 The DOM 19 iframes and other Ajax variations 20 JavaScript/Ajax Libraries 21 Server-side technologies 21 A look at Django 21 Django templating kickstart 22 A more complete glimpse at Django templating 23 Setting JavaScript and other static content in place 32 Summary 33 Chapter 2: jQuery—the Most Common JavaScript Framework 35 jQuery and basic Ajax 36 jQuery Ajax facilities 39 $.ajax() 39 context 40 data 42
  • 17. Table of Contents [ ii ] dataFilter 43 dataType 43 error(XMLHttpRequest, textStatus, errorThrown) 44 success(data, textStatus, XMLHttpRequest) 44 type 44 url 44 $.aj0axSetup() 45 Sample invocation 45 $.get() and $.post() 45 .load() 46 jQuery as a virtual higher-level language 48 The selectors 48 A closure-based example to measure clock skew 52 Case study: A more in-depth application 56 Chapter 3: Validating Form Input on the Server Side 56 Chapter 4: Server-side Database Search with Ajax 56 Chapter 5: Signing Up and Logging into a Website Using Ajax 57 Chapter 6: jQuery In-place Editing Using Ajax 57 Chapter 7: Using jQuery UI Autocomplete in Django Templates 57 Chapter 8: Django ModelForm: a CSS Makeover 57 Chapter 9: Database and Search Handling 57 Chapter 10: Tinkering Around: Bugfixes, Friendlier Password Input, and a Directory That Tells Local Time 58 Chapter 11: Usability for Hackers 58 Appendix: Debugging Hard JavaScript Bugs 58 Summary 58 Chapter 3: Validating Form Input on the Server Side 61 The standard lecture: low-level validation 62 Matching regular expressions 62 You cannot guarantee absolutely valid data 63 Validating can detect (some) malicious input 63 The Django way of validation 64 Django gives you some things for free 64 The steps in Django's validation 65 A more sensible and cruelty-free approach to validation 66 Things get murkier 67 The zero-one-infinity rule: a cardinal rule of thumb in usability 68 An improvement on Django's advertised approach 68 A validation example: GPS coordinates 70 Avoiding error messages that point fingers and say, "You're wrong!" 71
  • 18. Table of Contents [ iii ] Validation as demanding that assumptions be met 72 Old-school: conform to our U.S.-based assumptions! 72 Adding the wrong kind of band-aid 74 Making assumptions and demanding that users conform 76 At least names are simple, right? 76 Even in ASCII, things keep getting murkier 77 Better validation may be less validation 78 Caveat: English is something of a lingua franca 79 We don't have to negotiate with pistols 80 Doing our best to solve the wrong problem: a story 81 It really does apply to validation 82 Facebook and LinkedIn know something better 83 Summary 83 Chapter 4: Server-side Database Search with Ajax 85 Searching on the client side and server side 86 Handling databases through Django models 86 Models for an intranet employee photo directory 87 Searching our database 95 A tour of Django persistence facilities 100 Summary 103 Chapter 5: Signing Up and Logging into a Website Using Ajax 105 admin.py: administrative functions called once 107 functions.py: project-specific functions, including our @ajax_login_required decorator 107 views.py: functions that render web pages 108 style.css: basic styling for usability 113 search.html: a template for client-side Ajax 114 The Django admin interface 122 Summary 124 Chapter 6: jQuery In-place Editing Using Ajax 125 Including a plugin 127 How to make pages more responsive 127 A template handling the client-side requirements 128 The bulk of the profile 132 Whitespace and delivery 133 Page-specific JavaScript 136 Support on the server side 137 Summary 139
  • 19. Table of Contents [ iv ] Chapter 7: Using jQuery UI Autocomplete in Django Templates 141 Adding autocomplete: first attempt 142 Progressive enhancement, a best practice 142 A real-world workaround 146 "Interest-based negotiation": a power tool for problem solving when plan A doesn't work 146 A first workaround 148 Boilerplate code from jQuery UI documentation 154 Turning on Ajax behavior (or trying to) 156 Code on the server side 156 Refining our solution further 159 Summary 163 Chapter 8: Django ModelForm: a CSS Makeover 165 "Hello, world!" in ModelForm 165 Expanding and customizing the example 168 Customizing ModelForm pages' appearance 170 Going under ModelForm's hood 182 An excellent "stupid" question: where's the e-mail slot? 184 Summary 187 Chapter 9: Database and Search Handling 189 Moving forward to an AHAH solution 189 Django templates for simple AHAH 192 Templating for a list of search results 192 Template for an individual profile 195 Views on the server side 202 Telling if the user is logged in 202 A view to support deletion 202 The AHAH view to load profiles 203 Helper functions for the AHAH view for searching 204 An updated model 206 An AHAH server-side search function 207 Handling the client-side: A template for the main page 209 CSS for styling the directory 232 Our updated urlpatterns 241 Summary 241 Chapter 10: Tinkering Around: Bugfixes, Friendlier Password Input, and a Directory That Tells Local Time 243 Minor tweaks and bugfixes 243 Setting a default name of "(Insert name here)" 244 Eliminating Borg behavior 244
  • 20. Table of Contents [ ] Confusing jQuery's load() with html() 245 Preventing display of deleted instances 246 Adding a favicon.ico 249 Handling password input in a slightly different way 250 A directory that includes local timekeeping 252 Summary 260 Chapter 11: Usability for Hackers 261 Usability begins with anthropology… and Django hackers have a good start on anthropology 262 Anthropological usability techniques 263 An introductory example: card sorting 263 Focus groups: cargo cult research for usability 265 Anthropological observation: the bedrock of usability 265 More than one way to see the same situation 266 Applying this foundation to usability 268 It's just like (hard) debugging 271 Lessons from other areas 272 Live cross-cultural encounters 272 History 273 Old books and literature 274 The last other area: whatever you have 277 Understanding the user 278 A lesson from optimization 278 What's wrong with scratching an itch, or you are not your user 279 Worst practices from the jargon file 279 Python and usability 280 It's not all about the computer! 280 What to do in the concrete 282 Further reading 283 Summary 284 Appendix: Debugging Hard JavaScript Bugs 285 Just fiddling with Firebug is considered harmful 285 Cargo cult debugging at your fingertips 285 The scientific method of debugging 286 Exhausting yourself by barking up the wrong tree 287 The humble debugger 289 The value of taking a break 289 Two major benefits to asking for help 290
  • 21. Table of Contents [ vi ] Firebug and Chrome developer tools 290 The basics across browsers 290 Zeroing in on Chrome 293 Summary 298 Index 299
  • 22. Preface You want to create an AJAX application. Why would you use Django? Why would you use jQuery? Why would you use both together? Enter Django JavaScript Integration: AJAX and jQuery—your comprehensive answer to all these questions and the only extensive, practical, and hands-on guide to developing any AJAX application with Django and jQuery. Gone are the days when you used to lament over the lack of official documentation on AJAX with Django. This book will teach you exactly why Django is called The web framework for perfectionists with deadlines, how jQuery—the write less do more JavaScript library—is practically a virtual higher-level language, and why they both deserve to be integrated with AJAX. This hands-on-guide shows you how to put Django and jQuery together in the process of creating an AJAX application. In this book, they are brought together in a real-world scenario, with attention to usability, to build and develop an AJAX application. The first two chapters provide a short and necessary introduction to the world of Django, jQuery, and AJAX; the remaining chapters are based on a case study that will make you realize the immense potential and benefits of integrating Django and jQuery with your AJAX application. By the time you are done with this book, you'll be developing your AJAX applications with Django and jQuery in less time than you can say integrate. You will cover the basics of AJAX; use jQuery, the most common JavaScript library, on the client side, and learn form validation with an eye towards usability, build things with Django on the server side, handle login and authentication via Django-based AJAX, and then dip into the rich jQuery plugin ecosystem to build in-place editing into your pages.
  • 23. Preface [ ] You will add auto-complete functionality courtesy of jQuery UI, easily build forms with Django ModelForm, and then look at a client-side search implementation that can look things up without network access after initial download. You will learn to implement a simple, expandable undo system, and offer more full-blooded account management, tinker, fix some bugs, offer a more usable way to handle password input, add local time support for people who are not in your time zone, look at usability, and finally take a look at debugging. After working through this book, you will have both an AJAX application: a Web 2.0 employee intranet photo directory, and with it a deep understanding that you can use to customize, extend, and further develop it in your organization. What this book covers This book covers Django JavaScript integration and building an Ajax application with Django on the server side and jQuery on the client side. It provides first an overview, then a first Ajax application, and introduces jQuery; discusses form validation, server-side database search; Ajax login facilities; jQuery in-place editing and autocomplete, Django Modelform, and how to give auto-generated forms a transformational CSS makeover. It also discusses client-side functionality, customization, and further development with tinkering and added features, before a grand finale exploring usability, and an appendix on debugging hard JavaScript bugs. Chapter 1, jQuery and Ajax Integration in Django lays a solid foundation and introduces you to the working pieces of Django Ajax to be explored in the rest of the book. Chapter 2, jQuery—the Most Common JavaScript Framework explores the higher-level way of doing things in jQuery. You will learn how jQuery is not Python and does not look like Python, but how there is something Pythonic in spirit about how it works. Chapter 3, Validating Form Input on the Server Side will teach you how to send an Ajax request to the server via jQuery, and validate it on the server side based on the principle that all input is guilty until proven innocent of being malicious, malformed, incomplete, or otherwise invalid. Chapter 4, Server-side Database Search with Ajax looks both at the merits of handling searching and other backend functions with the full power of a backend environment, and explores why, on the client side, you should work hard to be as lazy as possible in doing network-related work.
  • 24. Preface [ ] Chapter 5, Signing-up and Logging into a Website Using Ajax introduces Django authentication facilities and account management and includes both server-side and client-side code. Chapter 6, jQuery In-place Editing Using Ajax goes from a basic foundation to a continuing practical application. It will show a way to use jQuery to make an in-place replacement of a table that allows in-place editing, which communicates with the server in the background, adding persistence to changes. Chapter 7, Using jQuery UI Autocomplete in Django Templates tells you what you need on the client side and server side to get autocomplete working with jQuery UI. It also includes creative problem solving when something goes wrong. This chapter will tell you why it is not uncommon for programmers to write plugins their first day doing jQuery. Chapter 8, Django ModelForm: a CSS Makeover explores Django ModelForm and how to use it. Chapter 9, Database and Search Handling covers all the bases for a simple, AHAH solution. In addition to showing lazy best practices, it also showcases a JavaScript in-memory database, with an application designed, at the developer's preference, to either always perform lazy handling of search and other requests, or start loading an in-memory database and falling back to lazy handling until the in-memory database is available. Chapter 10, Tinkering Around: Bugfixes, Friendlier Password Input, and a Directory That Tells Local Time covers some tinkering and tweaks, and bugfixes along the way Chapter 11, Usability for Hackers steps back from your application and takes a look at usability and the bedrock competencies hackers can leverage to do usability. Appendix, Debugging Hard JavaScript Bugs looks at the state of mind that is needed to debug difficult bugs. What you need for this book This book assumes a broad technical maturity and an ability to learn and integrate different skills. It helps to be a Pythonista with the usual strengths that come with Python, and knowledge of the Web. A basic understanding of, or the ability to learn, Django and JavaScript will be helpful. If you're a good generalist programmer who wants to learn Django JavaScript integration, this book is for you.
  • 25. Preface [ ] Who this book is for This book is for people looking to integrate AJAX / JavaScript functionality into their web applications. It is for Django users who are looking to easily integrate AJAX features into their applications. Conversely, it will also be a priceless companion for users familiar with Django and jQuery who are looking to integrate them in their AJAX applications. A working knowledge of Django and basic familiarity with AJAX and jQuery are assumed. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: You can override the empty string by setting TEMPLATE_STRING_IF_INVALID in your settings.py file. A block of code is set as follows: function outer() { result = 0; for(i = 0; i 100; ++i) { result += inner(i); } return result } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: def ajax_profile(request, id): entity = directory.models.Entity.objects.filter(id = int(id))[0] if entity.is_invisible: return HttpResponse(u'h2People, etc./h2') New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: ������� We can then click on Entity (or Locations), and add an entity�� . Warnings or important notes appear in a box like this.
  • 26. Preface [ ] 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 book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail [email protected]. 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 for the book 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/support, 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.
  • 27. Preface [ ] 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.
  • 28. jQuery and Ajax Integration in Django We will be working with the leading Python web framework, Django, on the server side, and jQuery-powered Ajax on the client side. During the course of this book, we will cover the basic technologies and then see them come together in an employee intranet photo directory that shares some Web 2.0 strengths. There is more than one good JavaScript library; we will be working with jQuery, which has reached acceptance as a standard lightweight JavaScript library. It might be suggested that Pythonistas may find much to like in jQuery: jQuery, like Python, was carefully designed to enable the developer to get powerful results easily. In this chapter, we will: Discuss Ajax as not a single technology but a technique which is overlaid on other technologies Cover the basic technologies used in Ajax JavaScript Cover Hello, world! in a Django kickstart Introduce the Django templating engine Cover how to serve up static content in Django Overall, what we will be doing is laying a solid foundation and introducing the working pieces of Django Ajax to be explored in this book. • • • • •
  • 29. jQuery and Ajax Integration in Django [ ] Ajax and the XMLHttpRequest object Ajax is not a technology like JavaScript or CSS, but is more like an overlaid function. So, what exactly is that? Human speech: An overlaid function Human speech is an overlaid function. What is meant by this is reflected in the answer to a question: What part of the human body has the basic job of speech? The tongue, for one answer, is used in speech, but it also tastes food and helps us swallow. The lungs and diaphragm, for another answer, perform the essential task of breathing. The brain cannot be overlooked, but it also does a great many other jobs. All of these parts of the body do something more essential than speech and, for that matter, all of these can be found among animals that cannot talk. Speech is something that is overlaid over organs that are there in the first place because of something other than speech. Something similar to this is true for Ajax, which is not a technology in itself, but something overlaid on top of other technologies. Ajax, some people say, stands for Asynchronous JavaScript and XML, but that was a retroactive expansion. JavaScript was introduced almost a decade before people began seriously talking about Ajax. Not only is it technically possible to use Ajax without JavaScript (one can substitute VBScript at the expense of browser compatibility), but there are quite a few substantial reasons to use JavaScript Object Notation (JSON) in lieu of heavy-on-the-wire eXtensible Markup Language (XML). Performing the overlaid function of Ajax with JSON replacing XML is just as eligible to be considered full-fledged Ajax as a solution incorporating XML. Ajax: Another overlaid function What exactly is this overlaid function? Ajax is a way of using client-side technologies to talk with a server and perform partial page updates. Updates may be to all or part of the page, or simply to data handled behind the scenes. It is an alternative to the older paradigm of having a whole page replaced by a new page loaded when someone clicks on a link or submits a form. Partial page updates, in Ajax, are associated with Web 2.0, while whole page updates are associated with Web 1.0; it is important to note that Web 2.0 and Ajax are not interchangeable. Web 2.0 includes more decentralized control and contributions besides Ajax, and for some objectives it may make perfect sense to develop an e-commerce site that uses Ajax but does not open the door to the same kind of community contributions as Web 2.0.
  • 30. Chapter 1 [ ] Some of the key features common in Web 2.0 include: Partial page updates with JavaScript communicating with a server and rendering to a page An emphasis on user-centered design Enabling community participation to update the website Enabling information sharing as core to what this communication allows The concept of partial page updates may not sound very big, but part of its significance may be seen in an unintended effect. The original expectation of partial page updates was that it would enable web applications that were more responsive. The expectation was that if submitting a form would only change a small area of a page, using Ajax to just load the change would be faster than reloading the entire page for every minor change. That much was true, but once programmers began exploring, what they used Ajax for was not simply minor page updates, but making client-side applications that took on challenges more like those one would expect a desktop program to do, and the more interesting Ajax applications usually became slower. Again, this was not because you could not fetch part of the page and update it faster, but because programmers were trying to do things on the client side that simply were not possible under the older way of doing things, and were pushing the envelope on the concept of a web application and what web applications can do. The technologies Ajax is overlaid on Now let us look at some of the technologies where Ajax may be said to be overlaid. JavaScript JavaScript deserves pride of place, and while it is possible to use VBScript for Internet Explorer as much more than a proof of concept, for now if you are doing Ajax, it will almost certainly be Ajax running JavaScript as its engine. Your application will have JavaScript working with XMLHttpRequest, JavaScript working with HTML, XHTML, or HTML5; JavaScript working with the DOM, JavaScript working with CSS, JavaScript working with XML or JSON, and perhaps JavaScript working with other things. • • • •
  • 31. jQuery and Ajax Integration in Django [ 10 ] While addressing a group of Django developers or Pythonistas, it would seem appropriate to open with, I share your enthusiasm. On the other hand, while addressing a group of JavaScript programmers, in a few ways it is more appropriate to say, I feel your pain. JavaScript is a language that has been discovered as a gem, but its warts were enough for it to be largely unappreciated for a long time. Ajax is the gateway drug to JavaScript, as it has been said—however, JavaScript needs a gateway drug before people get hooked on it. JavaScript is an excellent language and a terrible language rolled into one. Before discussing some of the strengths of JavaScript—and the language does have some truly deep strengths—I would like to say I feel your pain and discuss two quite distinct types of pain in the JavaScript language. The first source of pain is some of the language decisions in JavaScript: The Wikipedia article says it was designed to resemble Java but be easier for non-programmers, a decision reminiscent of SQL and COBOL. The Java programmer who finds the C-family idiom of for(i = 0; i 100; ++i) available will be astonished to find that the functions are clobbering each other's assignments to i until they are explicitly declared local to the function by declaring the variables with var. There is more pain where that came from. The following two functions will not perform the naively expected mathematical calculation correctly; the assignments to i and the result will clobber each other: function outer() { result = 0; for(i = 0; i 100; ++i) { result += inner(i); } return result } function inner(limit) { result = 0; for(i = 0; i limit; ++i) { result += i; } return result; } • •
  • 32. Chapter 1 [ 11 ] The second source of pain is quite different. It is a pain of inconsistent implementation: the pain of, Write once, debug everywhere. Strictly speaking, this is not JavaScript's fault; browsers are inconsistent. And it need not be a pain in the server-side use of JavaScript or other non-browser uses. However, it comes along for the ride for people who wish to use JavaScript to do Ajax. Cross-browser testing is a foundational practice in web development of any stripe; a good web page with semantic markup and good CSS styling that is developed on Firefox will usually look sane on Internet Explorer (or vice versa), even if not quite pixel-perfect. But program directly for the JavaScript implementation on one version of a browser, and you stand rather sharp odds of your application not working at all on another browser. The most important object by far for Ajax is the XMLHttpRequest and not only is it not the case that you may have to do different things to get an XMLHttpRequest in different browsers or sometimes different (common) versions of the same browser, and, even when you have code that will get an XMLHttpRequest object, the objects you have can be incompatible so that code that works on one will show strange bugs for another. Just because you have done the work of getting an XMLHttpRequest object in all of the major browsers, it doesn't mean you're home free. Before discussing some of the strengths of the JavaScript language itself, it would be worth pointing out that a good library significantly reduces the second source of pain. Almost any sane library will provide a single, consistent way to get XMLHttpRequest functionality, and consistent behavior for the access it provides. In other words, one of the services provided by a good JavaScript library is a much more uniform behavior, so that you are programming for only one model, or as close as it can manage, and not, for instance, pasting conditional boilerplate code to do simple things that are handled differently by different browser versions, often rendering surprisingly different interpretations of JavaScript. We will be using the jQuery library in this book as a standard, well-designed, lightweight library. Many of the things we will see done well as we explore jQuery are also done well in other libraries. We previously said that JavaScript is an excellent language and a terrible language rolled into one; what is to be said in favor of JavaScript? The list of faults is hardly all that is wrong with JavaScript, and saying that libraries can dull the pain is not itself a great compliment. But in fact, something much stronger can be said for JavaScript: If you can figure out why Python is a good language, you can figure out why JavaScript is a good language.
  • 33. jQuery and Ajax Integration in Django [ 12 ] I remember, when I was chasing pointer errors in what became 60,000 lines of C, teasing a fellow student for using Perl instead of a real language. It was clear in my mind that there were interpreted scripting languages, such as the bash scripting that I used for minor convenience scripts, and then there were real languages, which were compiled to machine code. I was sure that a real language was identified with being compiled, among other things, and that power in a language was the sort of thing C traded in. (I wonder why he didn't ask me if he wasn't a real programmer because he didn't spend half his time chasing pointer errors.) Within the past year or so I've been asked if Python is a real programming language or is just used for scripting, and something similar to the attitude shift I needed to appreciate Perl and Python is needed to properly appreciate JavaScript. The name JavaScript is unfortunate; like calling Python Assembler Kit, it's a way to ask people not to see its real strengths. (Someone looking for tools for working on an assembler would be rather disgusted to buy an Assembler Kit and find Python inside. People looking for Java's strengths in JavaScript will almost certainly be disappointed.) JavaScript code may look like Java in an editor, but the resemblance is a façade; besides Mocha, which had been renamed LiveScript, being renamed to JavaScript just when Netscape was announcing Java support in web browsers, it is has been described as being descended from NewtonScript, Self, Smalltalk, and Lisp, as well as being influenced by Scheme, Perl, Python, C, and Java. What's under the Java façade is pretty interesting. And, in the sense of the simplifying façade design pattern, JavaScript was marketed in a way almost guaranteed not to communicate its strengths to programmers. It was marketed as something that nontechnical people could add snippets of, in order to achieve minor, and usually annoying, effects on their web pages. It may not have been a toy language, but it sure was dressed up like one. Python may not have functions clobbering each other's variables (at least not unless they are explicitly declared global), but Python and JavaScript are both multiparadigm languages that support object-oriented programming, and their versions of object-oriented have a lot in common, particularly as compared to (for instance) Java. In Java, an object's class defines its methods and the type of its fields, and this much is set in stone. In Python, an object's class defines what an object starts off as, but methods and fields can be attached and detached at will. In JavaScript, classes as such do not exist (unless simulated by a library such as Prototype), but an object can inherit from another object, making a prototype and by implication a prototype chain, and like Python it is dynamic in that fields can be attached and detached at will. In Java, the instanceof keyword is important, as are class casts, associated with strong, static typing; Python doesn't have casts, and its isinstance() function is seen by some as a mistake, hence the blog posting isinstance() considered harmful at http://www.canonical.org/~kragen/isinstance/.
  • 34. Chapter 1 [ 13 ] The concern is that Python, like JavaScript, is a duck-typing language: If it looks like a duck, and it quacks like a duck, it's a duck! In a duck-typing language, if you write a program that polls weather data, and there's a ForecastFromScreenscraper object that is several years old and screenscrapes an HTML page, you should be able to write a ForecastFromRSS object that gets the same information much more cleanly from an RSS feed. You should be able to use it as a drop-in replacement as long as you have the interface right. That is different from Java; at least if it were a ForecastFromScreenscraper object, code would break immediately if you handed it a ForecastFromRSS object. Now, in fairness to Java, the best practices Java way to do it would probably separate out an IForecast interface, which would be implemented by both ForecastFromScreenscraper and later ForecastFromRSS, and Java has ways of allowing drop-in replacements if they have been explicitly foreseen and planned for. However, in duck-typed languages, the reality goes beyond the fact that if the people in charge designed things carefully and used an interface for a particular role played by an object, you can make a drop-in replacement. In a duck-typed language, you can make a drop-in replacement for things that the original developers never imagined you would want to replace. JavaScript's reputation is changing. More and more people are recognizing that there's more to the language than design flaws. More and more people are looking past the fact that JavaScript is packaged like Java, like packaging a hammer to give the impression that it is basically like a wrench. More and more people are looking past the silly toy language Halloween costume that JavaScript was stuffed into as a kid. One of the ways good programmers grow is by learning new languages, and JavaScript is not just the gateway to mainstream Ajax; it is an interesting language in itself. With that much stated, we will be making a carefully chosen, selective use of JavaScript, and not make a language lover's exploration of the JavaScript language, overall. Much of our work will be with the jQuery library; if you have just programmed a little bare JavaScript, discovering jQuery is a bit like discovering Python, in terms of a tool that cuts like a hot knife through butter. It takes learning, but it yields power and interesting results soon as well as having some room to grow.
  • 35. jQuery and Ajax Integration in Django [ 14 ] XMLHttpRequest The XMLHttpRequest object is the reason why the kind of games that can be implemented with Ajax technologies do not stop at clones of Tetris and other games that do not know or care if they are attached to a network. They include massive multiplayer online role-playing games where the network is the computer. Without having something like XMLHttpRequest, Ajax chess would probably mean a game of chess against a chess engine running in your browser's JavaScript engine; with XMLHttpRequest, Ajax chess is more likely man-to-man chess against another human player connected via the network. The XMLHttpRequest object is the object that lets Gmail, Google Maps, Bing Maps, Facebook, and many less famous Ajax applications deliver on Sun's promise: the network is the computer. There are differences and some incompatibilities between different versions of XMLHttpRequest, and efforts are underway to advance level-2-compliant XMLHttpRequest implementations, featuring everything that is expected of an XMLHttpRequest object today and providing further functionality in addition, somewhat in the spirit of level 2 or level 3 CSS compliance. We will not be looking at level 2 efforts, but we will look at the baseline of what is expected as standard in most XMLHttpRequest objects. The basic way that an XMLHttpRequest object is used is that the object is created or reused (the preferred practice usually being to reuse rather than create and discard a large number), a callback event handler is specified, the connection is opened, the data is sent, and then when the network operation completes, the callback handler retrieves the response from XMLHttpRequest and takes an appropriate action. A bare-bones XMLHttpRequest object can be expected to have the following methods and properties. Methods A bare-bones XMLHttpRequest object can be expected to have the following methods: 1. XMLHttpRequest.abort() This cancels any active request. 2. XMLHttpRequest.getAllResponseHeaders() This returns all HTTP response headers sent with the response. 3. XMLHttpRequest.getResponseHeader(headerName) This returns the requested header if available, or a browser-dependent false value if the header is not defined.
  • 36. Chapter 1 [ 15 ] 4. XMLHttpRequest.open(method, URL), XMLHttpRequest.open(method, URL, asynchronous), XMLHttpRequest.open(method, URL, asynchronous, username), XMLHttpRequest.open(method, URL, asynchronous, username, password) The method is GET, POST, HEAD, or one of the other less frequently used methods defined for HTTP. The URL is the relative or absolute URL to fetch. As a security measure for JavaScript running in browsers on trusted internal networks, a same origin policy is in effect, prohibiting direct access to servers other than one the web page came from. Note that this is less restrictive than it sounds, as it is entirely permissible for the server to act as a proxy for any server it has access to: for developers willing to undertake the necessary chores, other sites on the public internet are virtually accessible. The asynchronous variable defaults to true, meaning that the method call should return quickly in most cases, instead of waiting for the network operation to complete. Normally this default value should be preserved. Among other problems, setting it to false can lock up the visitor's browser. The last two arguments are the username and password as optionally specified in HTTP. If they are not specified, they default to any username and password defined for the web page. 5. XMLHttpRequest.send(content) Content can be a string or a reference to a document. Properties A bare-bones XMLHttpRequest object can be expected to have the following properties: 1. XMLHttpRequest.onreadystatechange, XMLHttpRequest.readyState In addition to the provided methods, the reference to one other method is supplied by the developer as a property, XMLHttpRequest.onreadystate- change, which is called without argument each time the ready state of XMLHttpRequest changes. An XMLHttpRequest object can have five ready states: Uninitialized, meaning that open() has not been called. Open, meaning that open() has been called but send() has not. Sent, meaning that send() has been called, and headers and status are available, but the response is not yet available. ° ° °
  • 37. jQuery and Ajax Integration in Django [ 16 ] Receiving, meaning that the response is being downloaded and responseText has the portion that is presently available. Loaded, meaning that the network operation has completed. If it has completed successfully (that is, the HTTP status stored in XMLHttpRequest.status is 200), this is when the web page would be updated based on the response. 2. XMLHttpRequest.responseText, XMLHttpRequest.responseXML The text of the response. It is important to note that while the name XMLHttpRequest is now very well established, and it was originally envisioned as a tool to get XML, the job done today is quite often to get text that may or may not happen to be XML. While there have been problems encountered with using XMLHttpRequest to fetch raw binary data, the XMLHttpRequest object is commonly used to fetch not only XML but XHTML, HTML, plain text, and JSON, among others. If it were being named today, it would make excellent sense to name it TextHttpRequest. Once the request reaches a ready state of 4 (loaded), the responseText field will contain the text that was served up, whether the specific text format is XML or anything else. In addition, if the format does turn out to be XML, the responseXML field will hold a parsed XML document. 3. XMLHttpRequest.status, XMLHttpRequest.statusText The status field contains the HTTP code, such as 200 for OK; the statusText field has a short text description, like OK. The callback event handler should ordinarily check XMLHttpRequest.readyState and wait before acting on server-provided data until the readyState is 4. In addition, because there could be a server error or a network error, the callback will check whether the status is 200 or something else: a code like 4xx or 5xx in particular needs to be treated as an error. If the server-response has been transmitted successfully, the readyState will be 4 and the status will be 200. This is the basic work that needs to be done for the XMLHttpRequest side of Ajax. Other frameworks may simplify this and do much of the cross-browser debugging work for you; we will see in the next chapter how jQuery simplifies this work. But this kind of task is something you will need to have done with any library, and it's worth knowing what's behind the simplified interfaces that jQuery and other libraries provide. ° °
  • 38. Chapter 1 [ 17 ] HTML/XHTML HTML and XHTML make up the bedrock markup language for the web. JavaScript and CSS were introduced in relation to HTML; perhaps some people are now saying that JavaScript is a very interesting language independent of web browsers and using standalone interpreters such as SpiderMonkey and Rhino. However, HTML was on the scene first and other players on the web exist in relation to HTML's story. Even when re-implemented as XHTML, to do HTML's job while potentially making much more sense to parsers, a very early web page, the beginning of the source at http://www.w3.org/History/19921103-hypertext/hypertext/WWW/ TheProject.html, is still quite intelligible: HEADER TITLEThe World Wide Web project/TITLE NEXTID N=55 /HEADER BODY H1World Wide Web/H1The WorldWideWeb (W3) is a wide-area A NAME=0 HREF=WhatIs.html hypermedia/A information retrieval initiative aiming to give universal access to a large universe of documents.P Everything there is online about W3 is linked directly or indirectly to this document, including an A NAME=24 HREF=Summary.htmlexecutive summary/A of the project, A NAME=29 HREF=Administration/Mailing/Overview.html Mailing lists/A , A NAME=30 HREF=Policy.htmlPolicy/A , November's A NAME=34 HREF=News/9211.htmlW3 news/A , A NAME=41 HREF=FAQ/List.htmlFrequently Asked Questions /A . DL … At the time of this writing, HTML 5 is taking shape but is not out in the wild, and so there are no reports of how the shoe feels after the public has worn it for a while. Code in this book, where possible, will be written in XHTML 1.0 Strict. Depending on your situation, this may or may not be the right decision for you; if you are working with an existing project, the right HTML/XHTML is often the one that maintains consistency within the project.
  • 39. jQuery and Ajax Integration in Django [ 18 ] XML eXtensible Markup Language (XML) is tied to an attempt to clean up early HTML. At least in earliest forms, HTML was a black sheep among specific markup languages derived from the generalized and quite heavy Standard Generalized Markup Language (SGML). Forgiving web browsers meant, in part, that early web hobbyists could write terrible markup and it would still display well in a browser. The amount of terrible markup on the web was not just an issue for purists; it meant that making a parser that could make sense of early Wild West web pages in general was a nearly impossible task. XML is vastly simplified from SGML, but it provides a generic space where an HTML variant, XHTML, could pick up the work done by HTML but not present parsers with unpredictable tag soup. XHTML could be described as HTML brought back into the fold, still good for doing web development, but without making machine interpretation such a hopeless cause. Where early HTML was developed with browsers that were meant to be forgiving, XML requested draconian error handling, and validated XML or XHTML documents are documents that can be parsed in a sensible way. XML works for exchanging information, and it works where many of its predecessors had failed: it provides interoperability between different systems after a long history of failed attempts at automating B2B communication and failed attempts at automated conversion between text data formats. Notwithstanding this, it is a heavy and verbose solution, with a bureaucratic ambiance, compared in particular to a lean, mean JSON. XML-based approaches to data storage and communication are increasingly critiqued in discussions on the web. If you have a reasonable choice between XML and JSON, we suggest that you seriously consider JSON. JSON JavaScript Object Notation (JSON) is a brilliantly simple idea. While formats like XML, ReStructuredText, and so on share the assumption that if you're going to parse this from your language, your language will need to have a parser added, JSON simply takes advantage of how an object would be specified in JavaScript, and clarifies a couple of minor points to make JSON conceptually simpler and cross-browser friendly. JSON is clear, simple, and concise enough that not only is it a format of choice for JavaScript, but it is gaining traction in other languages, and it is being used for communication between languages that need a (simple, added) parser to parse JSON. The other languages can't use eval() to simply run JSON, and in JavaScript you should have JSON checked to make sure it does not contain malicious JavaScript you should not eval(). However, JSON is turning out to have a much broader impact than the initial in communicating with JavaScript, just give it code to declare the object being communicated that can simply be evaluated to construct the object.
  • 40. Chapter 1 [ 19 ] CSS Cascading Style Sheets (CSS) may have introduced some new possibilities for presentation, but quite a lot of presentation was already possible beforehand. CSS did not so much add styling capabilities, as it added good engineering to styling (good engineering is the essence of separating presentation from content), and make the combination of semantic markup and attractive appearance a far more attainable goal. It allows parlor tricks such as in-place rebranding of websites: making changes in images and changing one stylesheet is, at least in principle, enough to reskin an extensive website without touching a single character of its HTML/XHTML markup. In Ajax, as for the rest of the web, the preferred practice is to use semantic, structural markup, and then add styles in a stylesheet (not inline) so that a particular element, optionally belonging to the right class or given the right ID, will have the desired appearance. Tables are not deprecated but should be used for semantic presentation of tabular data where it makes sense to use not only a td but a th as well. What is discouraged is using the side effect that tables can position content that is not, semantically speaking, tabular data. The DOM As far as direct human browsing is concerned, HTML and associated technologies are vehicles to deliver a pickled Document Object Model (DOM), and nothing more. In this respect, HTML is a means to an end: the DOM is the deserialized object, or better, the live form of what we really deliver to people. HTML may help provide a complete blueprint, and the complete blueprint is a means to the fully realized building. This is why solving Ajax problems on the level of HTML text are like answering the wrong question, or at least solving a problem on the wrong level. It is like deciding that you want a painting hung on a wall of a building, and then going about getting it by adding the painting to the blueprint and asking construction personnel to implement the specified change. It may be better to hang the painting on the wall directly, as is done in Ajax DOM manipulations. document.write() and document.getElementById().innerHTML() still have a place in web development. It is a sensible optimization to want a static, cacheable HTML/XHTML file include that will only be downloaded once in the usual multi-page visit. A JavaScript include with a series of document.write() may be the least Shanghaiing you can do to technologies and still achieve that goal. But this is not Ajax; it is barely JavaScript, and this is not where we should be getting our bearings. In Ajax, a serious alternative to this kind of solution for altering part of a web page is with the DOM. As the book progresses, we will explore Ajax development that works with the DOM.
  • 41. jQuery and Ajax Integration in Django [ 20 ] iframes and other Ajax variations Ajax includes several variations; Comet for instance, is a variation on standard Ajax in which either an XMLHttpRequest object's connection to a server is kept open and streaming indefinitely, or a new connection is opened whenever an old one is closed, creating an Ajax environment in which the server as well as the client can push material. This is used, for instance, in some instant messaging implementations. One much more essential Ajax variation has to do with loading documents into seamlessly integrated iframes instead of making DOM manipulations to a single, frame-free web page. If you click around on the page for a Gmail account, you will see partial page refreshes that look consistent with Ajax DOM manipulations: what happens when you click on Compose Mail, or a filter, or a message subject, looks very much like an Ajax update where the Gmail web application talks with the server if it needs to, and then updates the DOM in accordance with your clicks. However, there is one important difference between Gmail's behavior and a similar Ajax clone that updates the DOM for one frameless web page: what happens when you click the browser Back button. Normally, if you click on a link, you trigger an Ajax event but not a whole page refresh, and Ajax optionally communicates with a server and updates some part of the DOM. This does not register in the browser's history, and hitting the Back button would not simply reset the last Ajax partial page update. If you made an Ajax clone of Gmail that used DOM manipulations instead of seamlessly integrated iframes, there would be one important difference in using the clone: hitting Back would do far more than reverse the last DOM manipulation. It would take you back to the login or load screen. In Gmail, the browser's Back button works with surgical accuracy, and the reason it can do something much better than take you back to the login screen is that Gmail is carefully implemented with iframes, and every change that the Back button can undo is implemented by a fresh page load in one of the seamlessly integrated iframes. That creates browsing history. For that matter, a proof of concept has been created for an Ajax application that does not use client-side scripting or programming, instead using, on the client side, a system of frames/iframes, targets, links, form submissions, and meta refresh tags in order to perform partial page updates. Whether this variant technique lends itself to creating graceful alternatives to standard Ajax implementations, or is only a curiosity merely lending itself to proofs of concept, it is in principle possible to make an Ajax application that loses nothing if a visitor's browser has turned off scripting completely. Comet and iframes are two of many possible variations on the basic Ajax technique; what qualifies as Ajax is more a matter of Python- or JavaScript-style duck-typing than Java-style static typing. Asynchronous JavaScript and XML describes a reference example more than a strict definition, and it is not appropriate to say if
  • 42. Chapter 1 [ 21 ] you replace XML with JSON then, by definition, it isn't really Ajax. This is a case of, the proof of the pudding is in the eating, not what technologies or even techniques are in the kitchen. JavaScript/Ajax Libraries This book advocates taking advantage of libraries, and as a limitation of scope focuses on jQuery. If you only learn one library, or if you are starting with just one library, jQuery is a good choice, and it is widely used. It is powerful, but it is also a much easier environment to get started in than some other libraries; in that way, it is somewhat like Python. However, it is best not to ask, Which one library is best? but Which library or libraries are the right tools for this job?, and it is common real-world practice to use more than one library, possibly several. JavaScript libraries offer several advantages. They can reduce chores and boilerplate code, significantly lessening the pain of JavaScript, and provide a more uniform interface. They can also provide (for instance) ready-made widgets; we will be working with a jQuery slider later on in this book. And on a broad scale, they can let the JavaScript you write be higher-level and a little more Pythonic. Server-side technologies Many of the usual suspects in client-side technologies have been mentioned. The list of client-side technologies is generally constrained by what is available in common web browsers; the list of available server-side technologies is only constrained by what will work on the server, and any general-purpose programming language can do the job. The question on the server is not What is available? but Which option would you choose? Python and Django make an excellent choice of server-side technology, and we will work with them in this book. A look at Django Django's developers call it the web framework for perfectionists with deadlines, and it is one of the most popular Python web frameworks, perhaps the most popular. In contrast to the MVC pattern, which separates concerns into Model, View, and Controller, it could be described as an MTV pattern, which separates concerns into Model, Template, and View. The Model is a class that ties into an ORM where instances correspond to rows in the table but act and feel like Python objects. The Template is a system designed to be easy for non-Python developers (though easy for Pythonistas too), and limits the extent to which HTML needs to be sprinkled throughout the Python source. The View is a function that renders, in most cases, from a template. Let's look at a kickstart example of Django in action.
  • 43. jQuery and Ajax Integration in Django [ 22 ] Django templating kickstart Let us briefly go through how to install Django, create a sample project, and create and use a basic template that can serve as a basis for further tinkering. Django installation instructions are at http://docs.djangoproject.com/en/dev/ intro/install/; for Ubuntu, for instance, you will want to run sudo apt-get install python-django. Once you have Django installed, create a project named sample: django-admin.py startproject sample Go into the sample directory, and create the directory templates. Enter the templates directory. Create a template file named index.html containing the following template: !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www. w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US lang=en-US head title{% block title %}Hello, world!{% endblock title %} /title meta http-equiv=Content-Type content=text/html; charset=UTF-8 / /head body {% block body %} h1{% block heading %}Hello, world! {% endblock heading %}/h1 {% block content %}pGreetings from the Django templating engine!/p{% endblock content %} {% endblock body %} /body /html Go up one level to the sample directory and edit the urls.py file so that the first line after urlpatterns = patterns('', is: (r'^$', 'sample.views.home'), Then create the views.py file containing the following: #!/usr/bin/python/ from django.shortcuts import render_to_response def home(request): return render_to_response(u'index.html')
  • 44. Chapter 1 [ 23 ] Edit the settings.py file, and add: os.path.join(os.path.dirname(__file__), templates), right after: TEMPLATE_DIRS = ( Then, from the command line, run: python manage.py runserver This makes the server accessible to your computer only by entering the URL http://localhost:8080/ in your web browser. If you are in a protected environment behind a firewall, appropriate NATting, or the like, you can make the development server available to the network by running: python manage.py runserver 0.0.0.0:8080 There is one point of clarification we would like to make clear. Django is packaged with a minimal, single-threaded web server that is intended to be just enough to start exploring Django in a development environment. Django's creators are attempting to make a good, competitive web framework and not a good, competitive web server, and the development server has never undergone a security audit. The explicit advice from Django's creators is: when deploying, use a good, serious web server; they also provide instructions for doing this. A more complete glimpse at Django templating Before further exploring technical details, it would be worth taking a look at the opinions and philosophy behind the Django templating language, because an understandable approach of, Oh, it's a general purpose programming language used for templating, is a recipe for needless frustration and pain. The Django developers themselves acknowledge that their opinions in the templating language are one just opinion in an area where different people have different opinions, and you are welcome to disagree with them if you want. If you don't like the templating system that Django comes with, Django is designed to let you use another. But it is worth understanding what exactly the philosophy is behind the templating language; even if this is not the only philosophy one could use, it is carefully thought out.
  • 45. jQuery and Ajax Integration in Django [ 24 ] The Django templating language is intended to foster the separation of presentation and logic. In its design decisions, both large and small, Django's templating engine is optimized primarily for designers to use for designing, rather than programmers to use for programming, and its limitations are almost as carefully chosen as the features it provides. Unlike ASP, JSP, and PHP, it is not a programming language interspersed with HTML. It provides enough power for presentation, and is intended not to provide enough power to do serious programming work where it doesn't belong (in the Django opinion), and is simple enough that some non-programmers can pick it up in a day. For a programmer, the difficulty of learning the templating basics is comparable to the difficulty of simple HTML or SQL: it is simple, and a good bit easier to learn than wrapping your arms around a regular programming language. Some programmers like it immediately, but there are some who started by asking, Why doesn't the templating language just let you mix Python and HTML? and after playing with it, found themselves saying, This isn't what I would have come up with myself, but I really, really like it. Additional benefits include it being fast (most of the work is done by a single regular expression call, and the founders talk about disabling caching because it wasn't as fast as the template rendering), secure (it is designed so that it can be used by untrusted designers without allowing a malicious designer to execute arbitrary code), and versatile enough to generate whatever text format you want: plain text, HTML, XML, XHTML, JSON, JavaScript, CSV, ReStructuredText, and so on. We will be using it to generate web pages and JSON, but Django's templating language is a general-purpose text templating solution. Following the Django site's lead, let us use a template intended as an example of how one might begin a base template for a site, then start to walk through its contents, and then look at some of how it could be used and parts overridden to create a specific document. This renders as follows, if we strip out blank lines: !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www. w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US lang=en-US head title/title link rel=icon href=/https/www.slideshare.net/static/favicon.ico type=x-icon / link rel=shortcut icon href=/https/www.slideshare.net/static/favicon.ico type=x-icon / meta http-equiv=Content-Type content=text/html; charset=UTF-8 / meta http-equiv=Content-Language value=en-US /
  • 46. Chapter 1 [ 25 ] link rel=stylesheet type=text/css href=/https/www.slideshare.net/static/css/style.css / /head body div id=sidebar /div div id=content div id=header h1/h1 /div /div div id=footer /div /body script language=JavaScript type=text/javascript src=/static/js/jquery.js/script /html Let us unwrap what is going on here; there is more to the template than how it renders to this page, but let us start with that much. The {% block dtd %} style tags begin, or the case of {% endblock dtd %} end, a semantic block of text that can be left untouched or can be replaced. In the case of this one template, the effect is to strip them out like comments, but they will yield benefits later on, much like semantic HTML markup with CSS yields benefits later on. Django templating reflects a choice to go with hooks rather than includes because hooks provide the more versatile solution. The beginner's mistake version of a header to include might be something like the following: !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www. w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US lang=en-US head titleWelcome to my site!/title link rel=icon href=/https/www.slideshare.net/favicon.ico type=x-icon / link rel=shortcut icon href=/https/www.slideshare.net/favicon.ico type=x-icon / meta http-equiv=Content-Type content=text/html; charset=UTF-8 / meta http-equiv=Content-Language value=en-US / link rel=stylesheet type=text/css href=/https/www.slideshare.net/css/style.css / /head body
  • 47. jQuery and Ajax Integration in Django [ 26 ] This solution could be continued by adding a sidebar, but there is a minor problem, or at least it seems minor at first: there are bits of this header that are not generic. For a serious site, having every page titled, Welcome to my site! would be an embarrassment. The language is declared to be en-US, meaning U.S. English, which is wonderful if the entire site is in U.S. English, but if it expands to include more than U.S. English content, hardcoding en-US will be a problem. If the only concern is to accurately label British English, then the more expansive en could be substituted in, but hardcoding en-US and en are equally unhelpful if the site expands to feature a section in Russian. This header does not include other meta tags that might be desirable, such as description, which is ideally written for a specific page and not done as site-wide boilerplate. Including the header verbatim solves a problem, but it doesn't provide a very flexible solution. The previous example builds in hooks. It does specify: {% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml: lang=en-US lang=en-US{% endblock html_tag %} If not overridden, this will render as: html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-US lang=en-US However, in a template that extends this, by having {% extends base.html %} as its opening tag, if the base is loaded as base.html, then: {% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml: lang=en-GB lang=en-GB{% endblock html_tag %} will render: html xmlns=http://www.w3.org/1999/xhtml xml:lang=en-GB lang=en-GB And Russian may be declared in the same way: {% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml: lang=ru-RU lang=ru-RU{% endblock html_tag %} will render: html xmlns=http://www.w3.org/1999/xhtml xml:lang=ru-RU lang=ru-RU The template as given does specify en-US more than once, but each of these is inside a block that can be overridden to specify another language.
  • 48. Chapter 1 [ 27 ] We define initial blocks. First, the DTD: {% block dtd %}!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict// EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd {% endblock dtd %} Then, the HTML tag: {% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml: lang=en-US lang=en-US{% endblock html_tag %} Then we define the head, with the title and favicon: {% block head %}head title{% block title %}{{ page.title }} {% endblock title %}/title {% block head_favicon %}link rel=icon href=/https/www.slideshare.net/static/favicon.ico type=x-icon / link rel=shortcut icon href=/https/www.slideshare.net/static/favicon.ico type=x-icon /{% endblock head_favicon %} Then we define hooks for meta tags in the head. We define a Content-Type of UTF-8; this is a basic point so that non-ASCII content will display correctly: {% block head_meta %} {% block head_meta_author%}{% endblock head_meta_author %} {% block head_meta_charset %} meta http-equiv=Content-Type content=text/html; charset=UTF-8 / {% endblock head_meta_charset %} {% block head_meta_contentlanguage %} meta http-equiv=Content-Language value=en-US / {% endblock head_meta_contentlanguage %} {% block head_meta_description %} {% endblock head_meta_description %} {% block head_meta_keywords %} {% endblock head_meta_keywords %} {% block head_meta_othertags %} {% endblock head_meta_othertags %} {% block head_meta_refresh %} {% endblock head_meta_refresh %} {% block head_meta_robots %} {% endblock head_meta_robots %} {% endblock head_meta %} We declare a block to specify an RSS feed for the page: {% block head_rss %}{% endblock head_rss %}
  • 49. jQuery and Ajax Integration in Django [ 28 ] We add hooks for CSS, both at the site level, and section, and page. This allows a fairly fine granularity of control: {% block head_css %} {% block head_css_site %} link rel=stylesheet type=text/css href=/https/www.slideshare.net/static/css/style.css / {% endblock head_css_site %} {% block head_css_section %} {% endblock head_css_section %} {% block head_css_page %}{% endblock head_css_page %} {% endblock head_css %} We add section- and page-specific header information: {% block head_section %}{% endblock head_section %} {% block head_page %}{% endblock head_page %} Then we close the head and open the body: /head{% endblock head %} {% block body %} body We define a sidebar block, with a hook to populate it: div id=sidebar {% block body_sidebar %}{% endblock body_sidebar %} /div We define a block for the main content area: div id=content {% block body_content %} For the header of the main content area, we define a banner hook, and a header for the page's title, should such be provided. (If none is provided, there is no crash or error; the empty string is displayed for {{ page.title }}.) div id=header {% block body_header %} {% block body_header_banner %} {% endblock body_header_banner %} {% block body_header_title %}h1 {{ page.title }}/h1 {% endblock body_header_title %}
  • 50. Chapter 1 [ 29 ] We define a breadcrumb, which is one of many small usability touches that can be desirable: {% block body_header_breadcrumb %} {{ page.breadcrumb }} {% endblock body_header_breadcrumb %} {% endblock body_header %} /div We add a slot for announcements, then the body's main area, and then close the block and div: {% block body_announcements %} {% endblock body_announcements %} {% block body_main %}{% endblock body_main %} {% endblock body_content %} /div We define a footer div, with a footer breadcrumb, and a hook for anything our company's lawyers asked us to put: div id=footer {% block body_footer %} {% block body_footer_breadcrumb %} {{ page.breadcrumb }} {% endblock body_footer_breadcrumb %} {% block body_footer_legal %} {% endblock body_footer_legal %} {% endblock body_footer %} Now we close that div, the body, and the body block: /div /body{% endblock body %} We add a footer, with JavaScript blocks, again at the site/section/page level of hooks: {% block footer %} {% block footer_javascript %} {% block footer_javascript_site %} script language=JavaScript type=text/javascript src=/static/js/jquery.js/script {% endblock footer_javascript_site %} {% block footer_javascript_section %} {% endblock footer_javascript_section %} {% block footer_javascript_page %}
  • 51. jQuery and Ajax Integration in Django [ 30 ] {% endblock footer_javascript_page %} {% endblock footer_javascript %} {% endblock footer %} /html And that's it. You can make as many layers of templates as you want. One suggested approach is to make three layers: one base template for your entire site, then more specific templates for sections of your site (whatever they may be), and then individual templates for end use. The template given is a base template, and it provides hooks as narrow as a specific meta tag or as broad as the main content area. For our extended example, if it is named base.html, then we can create another template, russian.html, which will declare its content to be in the Russian language. (Ordinarily one would do more interesting things in overriding a template than merely replacing tags, but for illustration purposes we will do that, and only that: {% extends base.html %} {% block html_tag %}html xmlns=http://www.w3.org/1999/xhtml xml: lang=ru-RU lang=ru-RU{% endblock html_tag %} {% block head_meta_contentlanguage %}meta http-equiv=Content- Language value=ru-RU /{% endblock head_meta_contentlanguage %} These block overrides may occur anywhere; while the {% extends base.html %} tag must be placed first, the two tags may be swapped. It would work just as well to create a language-agnostic base.html with only an empty hook: {% block head_meta_contentlanguage %} {% endblock head_meta_contentlanguage %} and a default HTML tag of: html xmlns=http://www.w3.org/1999/xhtml And then create english.html and russian.html, or en-US.html and ru-RU.html, as base templates for those languages. However, there are many other tags than those used for blocks and overriding. We will just barely sample them below, looking at how to display variables, and then other tags.
  • 52. Chapter 1 [ 31 ] There are other tags that look like {% … %}, but I would comment briefly on the variable tags such as {{ page.title }}. The Django templating language uses dotted references, but not in exactly the same way as Python's dotted references. Where Python requires a couple of different things to get values, dotted references provide one-stop shopping in Django's templating. When a reference to {{ page. title }} occurs, it will display page[u'title'] if page[u'title'] is available. If not, it will display page.title if page.title is available as an attribute, and if there is no such attribute, it will display page.title() if page.title() is available, and failing that, if the reference is a non-negative integer like 2, it will display page[2] if page.2 is requested. If all of these fail, then Django defaults to the empty string because it's not acceptable for a professional site to crash because a programming error has the template asking for something that is not available. You can override the empty string by setting TEMPLATE_STRING_IF_INVALID in your settings.py file, and in development it may make sense to set TEMPLATE_STRING_IF_INVALID to something like LOOKUP FAILED, but you will want to set it back to the empty string for deployment in any production environment. At this point, while there are explicit hooks to pull in multiple JavaScript and CSS files, the preferred practice, per Steve Souders's ground rules for client-side optimizations for high performance websites, is: for each page to load initially, you should have one HTML/XHTML page, one CSS file included at the top, and one JavaScript file included at the bottom. The hooks are more flexible than that, but this is intended more as development leeway than what the tightened final product should be. If-then, if-then-else statements, and for loops are straightforward, and else clauses are optional: {% if results %} ul {% for result in results %} li{% result.title %}/li {% endfor %} /ul {% else %} pThere were no results./p {% endif %} There are a number of convenience features and minor variations available; these are several of the major features.
  • 53. jQuery and Ajax Integration in Django [ 32 ] Setting JavaScript and other static content in place For the development server, putting static content, including images, CSS, and static content, is straightforward. For production use, the recommended best practice is to use a different implementation, and Django users are advised to use a separate server if possible, optimized for serving static media, such as a stripped-down build of Apache, or nginx. However, for development use, the following steps will serve up static content: 1. Create a directory named static within your project. (Note that other names may be used, but do not use media, as that can collide with administrative tools.) 2. Edit the settings.py file, and add the following at the top, after import os: DIRNAME = os.path.abspath(os.path.dirname(__file__)) 3. Change the settings of MEDIA_ROOT and MEDIA_URL: MEDIA_ROOT = os.path.join(DIRNAME, 'static/') … MEDIA_URL = '/static/' 4. At the end of the settings.py file, add the following: if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'^%s(?Ppath.*)$' % (settings.MEDIA_URL[1:],), 'serve', { 'document_root': settings.MEDIA_ROOT, 'show_indexes': True }),) This will turn off static media service when DEBUG is turned off, so that this code does not need to be changed when your site is deployed live, but the subdirectory static within your project should now serve up static content, like a very simplified Apache. We suggest that you create three subdirectories of static: static/css, static/images, and static/js, for serving up CSS, image, and JavaScript static content.
  • 54. Chapter 1 [ 33 ] Summary Guido van Rossum, the creator of the Python programming language, for one project asked about different Python frameworks and chose the Django templating engine for his purposes (http://www.artima.com/weblogs/viewpost. jsp?thread=146606). This chapter has provided an overview of Ajax and then provided a kickstart introduction to the Django templating engine. There's more to Django than its templating engine, but this should be enough to start exploring and playing. In learning a new technology, a crucial threshold has been passed when there is enough of a critical mass of things you can do with a technology to begin tinkering, and taking one step often invites the question: What can we do to take this one step further?. In this chapter, we have provided a kickstart to begin working with the Django templating engine. In this chapter, we have looked at the idea of Pythonic problem solving, discussed Django and jQuery in relation to Pythonic problem solving, and discussed Ajax as not a single technology, but an overlaid function or technique that is overlaid on top of existing technologies. We have taken an overview of what the usual suspect technologies are for Ajax; given a kickstart to the Django templating engine, introducing some of its beauty and power; and addressed a minor but important detail: putting static content in place for Django's development server. This is meant to serve as a point of departure for further discussion of jQuery Ajax in the next chapter, and building our sample application. Interested readers who want to know more of what they can do can read the official documentation at http://docs.djangoproject.com/en/dev/topics/templates/. In the next chapter, we will push further and aim for a critical mass of things we can do. We will explore jQuery, the most common JavaScript library, and begin to see how we can use it to reach the point of tinkering, of having something that works and wondering, What if we try this?, What if we try that?, and being able to do it.
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. And now what must be the consequence? A derangement of business which it is difficult to imagine, a contraction of currency instantaneous and spasmodic to the amount of these large sums that I have indicated. I do not shrink from contraction. I am ready to say to the people of Massachusetts, “If the Senate will adopt any policy of contraction that is healthy, well-considered, and with proper conditions, I would recommend its acceptance.” But a contraction like that proposed by this bill, which arbitrarily takes from North and East this vast amount, and transfers it to another part of the country, where it may not be needed, such a contraction I oppose as mischievous. I see no good in it. I see a disturbance of all the channels of business; and I see a contraction which must be itself infinitely detrimental to the financial interests of the Republic. But then, Sir, have you considered whether you can do it? Is it practicable? I have shown that it is mischievous: is it practicable? Can you take this large amount of currency from one part of the country and transfer it to another? Have you ever reflected upon the history of the bank-note after it has commenced its travels, when it has once left the maternal bank? It goes you know not where. I have been informed by bank-officers, and by those most familiar with such things, that a bank-note, when once issued, very rarely returns home. I have been assured that it is hardly ever seen again. The banks, indeed, may go into liquidation, but their notes are still current. The maternal bank may be mouldering in the earth; but these its children are moving about, performing the work of circulation. Why? The credit of the nation is behind them; and everybody knows, when he takes one of them, that he is safe. Therefore, I ask, how can the proposed requirement be carried into execution? how can you bring back these runaways, when once in circulation on their perpetual travels? There is but one way, and that is by the return to specie payments. Hold up before them coin, and they will all come running back to the original bank; but until then they will continue abroad.
  • 57. The proposed requirement seems to go on the idea that bank-notes, like cows, return from pasture at night; whereas we all know, that, until specie payments, they are more like the wild cattle of the prairies and the pampas; you cannot find them; they are everywhere. Surely I am not wrong, when I suggest that the proposed requirement is impracticable as well as mischievous; and at the proper time I shall move to strike it out. The amendment which I have moved has been under discussion for several days. It has had the valuable support of the Senator from Michigan [Mr. Chandler], who brings to financial questions practical experience. It has been opposed by other Senators, and with considerable ardor by my excellent friend from Indiana [Mr. Morton]. On Thursday last, the Senator from Indiana, addressing himself to me, and inviting a reply, which I was then prevented from making, took issue with me directly upon the position I have assumed, that the withdrawal of legal-tender notes would materially assist the effort for specie payments; and he further declared that the two currencies of bank-notes and United States notes were kept together because one was redeemable with the other. I do not quote his precise words, but I give the substance.[220] Under the policy we are now pursuing, it seems to me, that, with $356,000,000 of legal-tender notes in circulation, the Government will not for many years, if ever again, pay specie. With that amount of United States notes, under the actual policy, the bank currency will forever remain inconvertible. And the correctness of these positions I will endeavor briefly to demonstrate. A convertible currency is nothing more nor less than the servant of coin. If there is no coin, it can neither be servant nor representative, though it may attempt to perform the functions of coin. Presenting itself under false pretences, it but partially succeeds in this attempt; and the discredit attaching to it compels it to pay more for any
  • 58. property than would be the price of such property in coin, or the acknowledged representative of coin,—just as doubtful people must submit to ten, fifteen, or twenty per cent. discount, when what is known as “gilt-edged” commercial paper is discounted at five, six, or seven per cent. Thus far we have had no coin in the Treasury appropriated to the stability of the United States notes,—and under our present policy, dictated by the restrictive laws that hedge the Secretary of the Treasury and confine his liberty of action, we never shall have, until the whole bonded debt of the country is extinguished,—while at the same time the banks are excused under the law from all attempts to fortify their notes with coin. And what is it that successfully discourages us from direct steps toward specie payments? In the first place, it is the mistrust of the people in our ability to resume, and to maintain resumption. In the next place, the monthly publication of the Treasury discloses precisely our weakness as well as our strength; and the great element of our weakness is the volume of our past-due and demand obligations. In ordinary times,— that is, when the people have confidence in the ability of the banks to redeem their demand obligations in coin,—a reserve of twenty to twenty-five per cent. in coin is more than sufficient to meet any probable demand that may be made. Let mistrust arise in relation to the solvency of any bank or of the system of banks, and the reserve of twenty-five per cent. will vanish as the dew before the sun, and the individual bank or all the banks must close their doors to all demands for specie. In our present legislation we encounter this mistrust wide-spread among the people; and so long as we ourselves exhibit so great timidity in our attempts at legislation upon this subject, just so long do we minister to and strengthen this mistrust. The amount of demand obligations which the Treasury must be prepared to meet upon a moment’s notice, including three per cent. certificates and fractional currency, is more than four hundred and
  • 59. forty million dollars. With the existing mistrust, measured by the premium on gold, a reserve of twenty-five per cent. of coin in the Treasury appropriated to these demands would be totally insufficient. This reserve must bear a proportion to the aggregate of liabilities so large as to remove mistrust, and this can be accomplished only by presenting as in the vaults of the Treasury an amount of coin nearly equal to the sum of liabilities. If during the last three years we had retained the surplus of coin that has reached the Treasury, we should now have enough; but, as a consequence of such accumulation, speculation would have run riot,—and I fear, if we should now by legislative enactment decree that course for the future, we should aggravate the situation. What, then, is left for us to do? What but to lessen our liabilities? —which, as the laws now stand, must remain the same to-morrow as to-day, and one, two, or five years hence immutably as now. Difficulties beset the contraction of those liabilities, as there are difficulties that impede the accumulation of coin in sufficient amount to meet our purpose; but the former may be neutralized, if not removed, by judicious compensations that will not in any serious degree retard the object for which I would legislate. Sound financial authorities unite in declaring, that, if the Government resumes specie payments, the banks of New York can resume; and when the banks of New York resume, the whole country can resume. Evidently, then, our care is the Government. And what is the first step? To my mind we must lessen the demand obligations of the Government, while the Secretary of the Treasury at the same time strengthens the reserves in the national vaults. Neither should be done suddenly or violently, but gradually, judiciously, and wisely. As the statutes now stand, the obligations cannot be reduced. With the present volume of obligations, the laws of trade prevent the Secretary of the Treasury from sufficiently strengthening his reserves. It therefore devolves upon the National
  • 60. Legislature to take the initiative in the effort to resume specie payments. The difficulties that impede the reduction of the national liabilities lie in the fact that such obligations are a part, and a large part, of the currency of the country. To withdraw that currency without giving a substitute is to create stringency, burden trade, and invite chaos: at least, so it seems. These obligations, so far as they relate to the currency, are larger in amount than those of the national banks combined; and furthermore, they are the head and front of all. They are so large as to be beyond the point of manageability, and I would therefore reduce them within control. It is their volume that puts them beyond control, and it is our want of control that causes them to be depreciated. Thus, Sir, I would offer inducements to fund them, or part of them, in bonds that would be sought after because of their valuable uses beyond a mere investment, and to neutralize the evils of contraction of Treasury liabilities by authorizing their assumption, with the consent of the people, by various parties in different sections of the country, each one of whom would be fully equal to the task thus voluntarily assumed. I would issue a bank- note for every dollar of Treasury obligation cancelled; but I would issue no bank-note that did not absorb an equal obligation of the Treasury. By this distribution of a portion of the demand obligations you restore to the Government the full ability to meet the remainder; and at the same time the people know, that, so far as the currency goes,—and it is of this only we are treating,—every promise of any bank has its ultimate recourse in the Treasury of the United States. The absorption of one hundred and fifty or two hundred millions cannot fail to enhance the remaining legal-tender nearly, if not quite, to par with gold. The volume of currency in the channels of trade and in the hands of the people will be about the same as now. The aggregate of United States notes and national bank-notes outstanding will be precisely the same. Therefore the indirect contraction so much dwelt upon will scarcely be felt. The volume of greenbacks will be ample for the reserves of the banks, and their
  • 61. growing scarcity will cause them to become more and more valuable; and as they approach the standard of gold, so will they sustain with golden support the bank-notes into which they are convertible. The demand by the people for legal-tender will not be appreciably increased, as the bank-note is receivable by the Government for all dues except customs, and those demands are necessarily localized. While the growing scarcity of greenbacks, because of their replacement by bank-notes fulfilling all the requirements of general trade, will not be noticed by the people, the banks will take heed lest they fall, and at an early day begin to strengthen themselves. Legal- tender reserves they must have, and, with the honest eyes of our Secretary of the Treasury to detect any deficiency, they will begin their strengthening policy at once. Instead of putting gold received as interest forthwith on the market for sale, they will put it snugly away in their vaults. The gold which comes to them in the course of banking operations will be added thereto; and almost imperceptibly the country banks will arrive at the condition of the city banks, whose reserves in coin and legal-tender notes are now far beyond the requirements of law. In the mean time, and without derangement of business, the Treasury may strengthen its reserve,— while, on the other hand, the quiet reduction of its liabilities advances the percentage of the reserve to the whole amount of liabilities in almost a compound ratio. With this strengthening of the condition of the Treasury, made manifest to all the world by its monthly publications, the mistrust of the people will be gradually, but surely, dissipated, and as surely be replaced by confidence that all demand obligations will be redeemed at an early day,—a confidence as wide-spread and deep-seated as is that now prevailing in relation to our bonded debt, that it will be paid according to the spirit as well as the letter of the law. It will thus be seen that just in proportion to the strengthening of the legal-tender do we strengthen the bank-note. Strike out of existence in a single day the legal-tender notes, and I fear that the
  • 62. bank-note would for a time fall in comparative value: so would everything else. But I advocate no such violent measure. The Senator from Indiana in his remarks appeared to forget that we have in the country two or three hundred millions of another legal-tender,—being coin, now displaced, of which no legitimate use is made in connection with the currency,—that should resume its proper position in the paper circulation of the country. Here are two or three hundred millions of money, now by force of law demonetized, which I would have relieved of its disabilities. I would change the relation of master it now occupies to that of servant, where it properly belongs; and I would inflate the currency with it to the extent that we possess it. Inflation by coin is simply specie payment, or very near it. I have endeavored, Mr. President, thus briefly to respond to the questions propounded to me. I do not know that I have entered sufficiently into detail to explain clearly my convictions as to the necessity for reducing the volume of legal-tender obligations, and to prove, as I desire to prove, that their gradual withdrawal will enhance not only the value of the remainder, but also the value of the bank-note. Both will ascend in the scale. This enhancement of the whole paper currency will tend to draw the coin of the country from its seclusion. As in the early period of the war, before the present currency was created, we were astonished at the positive, but hidden, money resources of the people, so will the outflow of hidden coin confound the calculations of those who suppose that its volume is to be measured by the amount in the Treasury and in the New York banks. Mr. President, I am not alone in asking for the reformation of our currency as the first stage of our financial efforts. I read from the “Commercial and Financial Chronicle”[221] of New York, an authoritative paper on this subject, as follows:—
  • 63. “In any practical scheme to improve the Government finances and credit, or to restore prosperous activities, or both at once, the first thing to be done must be the restoration of a sound currency. That done or provided for, all the rest will be easy; the best credit and the lowest rates of interest will follow.” To this end our greenbacks must be absorbed or paid, and my proposition provides a way. As the greenbacks are withdrawn, coin will reappear to take their place in the banks and the business of the country. This will be specie payments. Here I wish to remark that I fail to see the asserted dependence of our demand notes on our bonds. The bonds may be at par without bringing the notes to par, and so the notes may be at par without bringing the bonds to par. According to the experience of other countries, bonds and notes do not materially affect each other. The two travel on parallel lines without touching. Each must be provided for; and my present purpose is to provide for the demand notes. There is strong reason why this is the very moment for this effort. According to statistical tables now before me, our exports are tending to an equality with our imports. During the five months of July, August, September, October, and November, 1869, there has been a nominal balance in our favor of $1,752,416; whereas during the same months of last year there was an adverse balance of $32,163,339. The movement of specie is equally advantageous. During the five months above mentioned there has been an import in specie of $10,056,316 against $5,273,116 during the same months last year, and an export in specie of $19,031,875 against $21,599,758 during the same months last year.[222] According to these indubitable figures, the tide of specie as well as of business is beginning to turn. It remains for us by wise legislation to take advantage of the propitious moment. Take the proper steps and you
  • 64. will have specie payments,—having which, all the rest will follow. Because I desire to secure this great boon for my country I now make this effort. The amendment was rejected. March 2d, Mr. Sumner’s bill having been reported back from the Committee on Finance with an amendment in the nature of a substitute, he spoke in review of their respective provisions as follows:— Mr. President,—The measure now before the Senate concerns interests vast in amount and influence. I doubt if ever before any nation has attempted to deal at once with so large a mass of financial obligations, being nothing less than the whole national debt of the United States. But beyond the proper disposition of this mass is the question of taxation, and also of the extent to which the payment of the national debt shall be assumed by the present generation, and beyond all is the question of specie payments. On all these heads my own conclusions are fixed. The mass of financial obligations should be promptly adjusted in some new form at smaller interest; taxes must be reduced; the payment of the national debt must be left in part to posterity; specie payments must be provided for. The immediate question before the Senate is on a substitute reported by the Committee for the bill which I had the honor of introducing some weeks ago. Considering my connection with this measure, I hope that I shall not intrude too much, if I recur to the original bill and explain its provisions. There are certain general objects which must not be forgotten in our present endeavor. I have already said that the taxes must be reduced. Here I am happy to observe that the popular branch of Congress, in the exercise of its constitutional prerogative, has taken the initiative and is perfecting measures to this end. I trust that they will proceed prudently, but boldly.
  • 65. In harmony with this effort the expenditures of the Government should be revised and cut down to the lowest point consistent with efficiency. Economy will be an important ally. Even in small affairs it will be the witness to our purposes. Through these agencies our currency will be improved, and we shall be brought to specie payments, while the national credit will be established. Not at once can all this be accomplished, but I am sure that we may now do much. As often as I return to this subject I am impressed by the damage the country has already suffered through menacing propositions affecting the national credit. I cannot doubt that in this way the national burdens have been sensibly increased. By counter- propositions in the name of Congress we have attempted to counteract these injurious influences. We have met words with words. But this is not enough. There is another remark which I wish to make, although I do little more than repeat what I said on another occasion.[223] It is that a national debt, when once funded, does not seem to affect largely the condition of the currency. The value of the former is maintained or depressed by circumstances independent of the currency. But, on the other hand, the condition of the currency bears directly upon all efforts for increased loans; and this is of practical importance on the present occasion. The rules of business are the same for the nation as for an individual; nor can a nation, when it becomes a borrower, hope to escape the scrutiny which is applied to an individual under similar circumstances. Applying this scrutiny to our case, it appears that on our existing bonded debt we have thus far performed all existing obligations,—not without discussion, I regret to add, that has left in some quarters a lingering doubt with regard to the future, and not without an opposition still alive, if not formidable. But the case is worse with regard to that other branch of the national debt known as legal-tenders, where we daily fail to perform existing obligations, so that these notes are nothing more than so much failed paper. With regard to this branch of the national debt there is
  • 66. an open confession of insolvency, and each day renews the confession. Now, by the immutable laws of credit, which all legislative enactments are impotent to counteract or expunge, the nation must suffer when it enters the market as a borrower. Failing to pay these obligations already due, it must pay more for what it borrows. Nor can we hope for more than partial success, until this dishonor is removed. With these preliminary remarks, which are rather hints than arguments, I come directly to the measure before the Senate; and here I begin with the first section. I wish the Senate would note the difference between this section in my bill and in the substitute of the Committee. I proposed to authorize the issue of $500,000,000 of Ten-Forty five per cents., and prescribe the use to which the proceeds of such bonds should be applied. The Committee propose $400,000,000 of Ten-Twenty five per cents., and leave the application of the proceeds the subject of discretion. Between the two propositions there are several differences: first, in the amount; secondly, in the length of the bond; and, thirdly, in the application of the proceeds. Here I beg to observe that the original sum of $500,000,000 was not inserted by accident, or because it was a round and euphonious sum. Nothing of the kind. It was the result of a careful examination of the national debt in its details, especially in the light of the national credit. It was adopted because it was the very sum required by the nature of the case. At least so it seemed to me. A brief explanation will show if I was not right. The year 1862, which marks the date of our legal-tenders, marks also the date of a new system in regard to our loans. Senators are hardly aware of this change. Previously our standard for sixes was an immutable loan for twenty years. By the new system this immutability was continued as to the right of demand by the
  • 67. bondholder, but the right of payment was reserved to the nation at any time after five years. This change, as we now see, gave positive advantages to the nation. Its disadvantages to the bondholder were so apparent that it encountered resistance, which was overcome only after undaunted perseverance and final appeal to the people. Now, by recurring to the schedule of the national debt, you will find that the first loan within the sphere of this discretionary system is the Five-Twenties of 1862, which, on the 1st of February last, after deducting the purchased bonds, were $500,000,000. This, therefore, is the first loan falling within our discretion, the first loan we are privileged to pay before maturity, and the first loan presenting itself for payment. In these incidents the loan of 1862 has precedence,—it stands first. But there is a reason, which to my mind is of peculiar force, why this first loan should be paid in coin at the earliest possible day. It seems to me that I do not deceive myself, when I consider it conclusive on this question. The loan of 1862 is the specific loan which has been made the objective point of all the movements under the banner of Repudiation. It is the loan to which this idea first attached itself. It is the loan first menaced. Therefore, to my mind, it is the loan which should be first provided for. I know no way, short of universal specie payments, by which the national credit can be so effectually advanced. Why in the amendment of the Committee the amount of the proposed issue is placed at $400,000,000 I am at a loss to conceive. Here is no equivalent of any one loan, nor of two or more loans. It is an accidental sum, and might have been more or less for the same reason that it is what it is. The term Ten-Twenties seems also accidental, as it is unquestionably new. Of course it is assumed that the amount proposed of Ten-Twenties at five per cent. will absorb an equal amount of Five-Twenties at six per cent., irrespective of any particular loan; but I am at a loss to see on what grounds the holders of the sixes can be induced to make the exchange. Will the substitute bonds be considered of equal value? I affirm not. But
  • 68. assuming that they are acceptable, how shall they be acceptably distributed? Shall the first comer be first served? If all were at the same starting-point, the palm might be justly bestowed upon the most swift. In the latitude allowed, stretching over all the Five- Twenties, there would be opportunity for favoritism; and with this opportunity there would be temptation and suspicion. The change from a Ten-Forty bond to a Ten-Twenty bond, as proposed by the Committee, is a change, so far as I can perceive, made up of disadvantages. To the nation there is the same rate of interest, and there is the same fixed period during which this interest must be paid; while, on the other hand, the period of optional payment is reduced from thirty years to ten years. If there be advantage in this reduction, I do not perceive it. If at the expiration of ten years we are in a condition to pay, we may do so as readily under a Ten-Forty as under the Ten-Twenty proposed. If during the subsequent ten years of option our advancing credit enables us to command a lower rate of interest, surely we may do so just as favorably under one as under the other. There is no benefit within the bounds of imagination, so far at least as I can discern, which will not redound to the nation from Ten-Forties as much as from Ten- Twenties. On the other hand, it is within possibilities, from disturbance in the money markets of the world, or from other unforeseen circumstances, that it may not be convenient during the short optional period of the Committee to obtain the necessary coin without a sacrifice. The greater latitude of payment leaves the nation master of the situation, to pay or not to pay, as is most for the national advantage. Furthermore, the loan proposed by the Committee has not, to my mind, the elements of success promised by the other loan. It is assumed in both cases that the coin for the redemption of the existing obligations shall be obtained in Europe. Then we must look to the European market in determining the form of the new loan. Now I have reason to believe that a coin loan to the amount of $500,000,000 may be obtained in Europe on Ten-Forties at par,
  • 69. provided the new bonds are of the same form and purport as the Ten-Forties which are already so popular, and provided further that the proceeds of the loan are applied to the payment in coin at par of the Five-Twenties of 1862. The reasons are obvious. The Ten-Forties have a good name, which is much to start with. It is like the credit or good-will of an established mercantile house, which stands often instead of capital; and then the fact that the proceeds are to be absorbed in the redemption of the first Five-Twenties, so often assailed, will most signally attest the determination of the country to maintain its credit. These advantages cost nothing, and it is difficult to see why they should be renounced. We must not make an effort and fail. Our course must be guided by such prudence that success will be at least reasonably certain. For the nation to offer a loan and be refused in the market will not do. Here, as elsewhere, we must organize victory. Now it is to my mind doubtful, according to the information within my reach, if the loan proposed by the Committee can be negotiated successfully at par. Bankers there may be who would gladly see themselves announced as financial agents of the great Republic; but it remains to be seen if there are any competent to handle a loan of $500,000,000 who would undertake it on the terms of the Committee. I am clear that it is not prudent to make the experiment, when it is easy to offer another loan with positive advantages sufficient to turn the scale. Washington, in his Farewell Address, said, “Why forego the advantages of so peculiar a situation? Why quit our own to stand upon foreign ground?” In the same spirit I would say, Why forego the advantages of a well-known and peculiar security? Why quit our Ten-Forties to stand upon a security which is unknown, and practically foreign, whether at home or abroad? In the loan proposed by the original bill we find assurance of success, with the promise of reduced taxation, Repudiation silenced, and the coin reserves in the banks strengthened by sales in Europe, it may be, $150,000,000. Should the amendment of the Committee prevail, I see small chance of any near accomplishment of these
  • 70. objects, and meanwhile our financial question is handed over to prolonged uncertainty. I pass now to the substitute of the Committee for the second and third sections of the original bill. Here again the amount is changed from $500,000,000 to $400,000,000. I am not aware of any reason for this change; nor is there, indeed, any peculiar reason, as in the case of the Five-Twenties of 1862, for the amount of $500,000,000. The question between the two amounts may properly be determined by considerations of expediency, among which will be that of uniformity with outstanding loans. A more important change is in the time the bonds are to run, which is Fifteen-Thirty years for the bonds at four and a half per cent., and Twenty-Forty years for the bonds at four per cent. Here occurs again the argument with regard to the inferiority of Ten-Twenties, as compared with Ten-Forties. By the same reason the Fifteen-Thirties will be inferior to the Fifteen-Fifties, and the Twenty-Forties will be inferior to the Twenty-Sixties, of the original bill. The prolongation of the bond is in the nature of compensation for the reduction of interest. Already we have established the ratio of compensation for such reduction,—already for a loan at six per cent. we have offered Five-Twenties, but for a loan at five per cent. we have offered Ten-Forties,—and I see no reason why by a tentative process we should so materially change this standard as is now proposed. The experiment can do no good, while it may do harm. It is in the nature of a restriction on our discretion, and a limitation of the duration of the bond, which, I apprehend, must interfere essentially with its marketable character. While the prolongation of time enlarges the option of the nation, it increases the value of the bond in the market. That which is most favorable to the nation is most favorable to the market value of the bond; and that which is unfavorable to the nation is unfavorable also to the market value of the bond, rendering its negotiation and sale more difficult and protracted. Thus at every turn are we brought back to the original proposition.
  • 71. Against this conclusion is the argument founded on the idea of English consols. It is sometimes said, If the short term of Five- Twenty years is the standard for a six per cent. bond with a graduation to Twenty-Sixty for a four per cent. bond, why may we not go further, and establish consols at three per cent., running, if you please, to eternity?—The technical term “consols” is an abbreviation for the consolidated debt of Great Britain, and in the eyes of a British subject has its own signification. It means a debt never to be paid, or at least it is an inscribed debt carrying no promise of payment. I would not have any debt of the United States assume either the form or name of consols. I would rigidly adhere to definite periods of payment. This is the American system, in contradistinction to the British system. I would not only avoid the idea that our debt is permanent, but I would adhere to the form of positive payment at some fixed period, and keep this idea always present in the minds of the people. Without the requirement of law, I doubt if the debt would be paid. Political parties would court popularity by a reduction of taxation. The Treasury of the United States, like the British Treasury, would always be without a surplus, and the national debt would be recognized as a burden to be endured forever. Therefore do I say, No consols. There is another consideration, having a wide influence, but especially important at the West and South, which should induce us to press for a reduction of the interest on our bonds; and here I present an argument which, if not advanced before, is none the less applicable. Do Senators consider to what extent the Government determines the rates of interest in the money centres of the country? Not only for itself does it determine, but for others also. Government bonds enjoy preëminence as an investment,—and if the interest is high, they attract the disposable money of the country. Government sixes are worth more than a six per cent. bond of any private corporation or individual, no matter how well secured. Therefore, it is easy to see, so long as we retain our standard at six per cent., so long as we
  • 72. have sixes, will the capital of the country seek these bonds for investment, permanent or temporary, to the detriment of numerous enterprises important to the national development, which are driven to be the stipendiaries of foreign capital. Railroads, especially at the West and South, are sufferers, being sometimes delayed by the difficulty of borrowing money, and sometimes becoming bankrupt from ruinous rates of interest, always in competition with the Government. But what is true of railroads is also true of other enterprises, which are pinched, and even killed, by these exactions in which the Government plays such a part. All are familiar with the recurring appeals for money on bonds even at eight per cent., which is more than can be paid permanently without loss; and even at such a ruinous rate there is difficulty in obtaining the required amount. Doubtless the excessive interest now demanded is partly due to our fictitious currency, where failed paper is forced upon the market; but beyond this influence is that of our sixes, absorbing disposable capital. I venture to assert, that, if we could at an early day reduce these sixes to fives, there are millions which would be released to seek investment in other securities at six per cent., especially to the relief of the West and South. The reduction of interest to four and a half per cent. and four per cent. would release further millions. A recent incident in the financial history of Massachusetts illustrates the disturbing influence of our sixes. An attempt to obtain a loan in Europe at five per cent. was unsuccessful, chiefly because the National Government offered six per cent. Therefore, for the sake of public enterprise in its manifold forms, for the sake of that prosperity which depends on human industry, for the sake of manufactures, for the sake of commerce, and especially for the sake of railroads, by which all these are quickened, we must do what we can to reduce the general rate of interest, which is now such a curb on enterprise; and here we must begin with our own bonds. Without any adverse intention, the National Government is a victorious competitor, and the defeated parties are those very
  • 73. enterprises whose success is so important to the country. A competition so destructive should cease. Keeping this before us in the new loan, we shall adopt that form of bond by which the interest will most surely be reduced. Thus, while refunding the national debt, we shall open the way to improvements of all kinds. This is what I have to say for the present on the refunding propositions of the Committee. Their object is the same as mine. If I differ from them in details, it is because after careful consideration it seems to me that in some particulars their system may be improved. Proceeding from these pivotal propositions, I find other things where I must again differ. When I first addressed the Senate on this subject, I took occasion to declare my objection to the idea of agencies or offices in the commercial centres of Europe, where interest should be paid. I am not ready to withdraw that objection,— though, if I could be tempted, it would be by the Senator from Ohio [Mr. Sherman], when he held up the prospect of a common money among nations. This is one of the desires of my heart, as it is one of the necessities of civilization; but I fail to see how this aspiration will be promoted by the system proposed,—which must be judged on its own merits, without any such recommendation. It is easy to see that such a system, besides being the beginning of a new policy on the part of the Government, may entail serious embarrassments. Sub- treasuries must be created in foreign capitals, which must be continued so long as the bonds last. Remittances of coin must be semiannual; and should such remittances fail at any time, there must be advances at no little cost to the Government. I cannot imagine any advantage from this new system sufficient to induce us to encounter the possible embarrassments or entanglements which it may cause.
  • 74. I would not take too much of the time of the Senate, and therefore I pass at once to the proposition of the Committee, being section seven, providing for the very early payment of the national debt. Mr. President, the payment of the national debt is an American idea, and I would say nothing to weaken it among the people. Whatever we owe must be paid; but it is the part of prudence to make the payment in such way as, while consistent with our obligations, shall promote the national prosperity. In this spirit I approach the proposition of the Committee, in which there is so much of good, only to examine and measure it, in order to ascertain its probable influence, especially on the question of Taxation. Here it must be borne in mind, that the present measure in all its parts, so far as applicable, and especially with its guaranties and pledges, must be taken as the basis of our new engagements. The provision that so much of the debt shall be paid annually will become in a certain sense a part of the contract, although not so expressed in the bond. Not less than $150,000,000 are set apart annually to be applied “to the payment of the interest and to the reduction of the principal of the public debt.” This is a large sum, and we should consider carefully if such a guaranty or pledge has in it the promise of financial stability. Promising too much is sometimes as bad as promising too little. Our promise must be according to our means prudently employed. If we assume obligations so large as to bear heavily upon the business of the country and to compel unreasonable taxation, there will be little chance of financial stability. They will become the object of attack, and will enter into the conflict of parties,—and if repealed, the national faith may be called in question. I need not say that business must suffer. A less ambitious effort on our part will be less obnoxious to attack,—thus leaving the bonds to their natural position in the money market, and strengthening all the movements of commerce.
  • 75. In order to determine the operation of this provision we must look into details. I have the estimates before me, showing our present and prospective liabilities for interest; but I content myself with presenting compendiously the result, in order to determine the question of taxation. Suffice it to say, that under the operation of the present measure there will be in 1871, after the payment of all liabilities for interest, a surplus of $43,000,000 to be applied to the payment of the national debt. With each succeeding year the reduction of interest will rapidly increase this surplus; and when we bring into operation other provisions of the bill, and convert $500,000,000 of sixes into a like amount of four and a half per cents., effecting a further saving of interest, equal to $7,500,000 annually, the surplus revenue, as compared with necessary expenditures, will in a brief period approach $100,000,000 annually. Here the question arises, Is not this unnecessarily large? Is it not beyond the bounds of prudence and wise economy? Shall we declare in this fundamental measure a determination to redeem the whole national debt within a period of twenty-five years? Can the industries of the country sustain such taxation? I put the question. You shall answer it. The future has its great claims upon us; so also has the present. I submit that the pending measure sacrifices the present. I conclude, therefore, as I began, with another appeal for reduced taxation. At the proper time I shall move an amendment, in order to aid this result. In the course of the proceedings which followed, the bill of the Committee underwent important amendments, in accordance with the views expressed by Mr. Sumner,—for the Ten-Twenties and Fifteen-Thirties therein proposed, a prolongation to Ten-Forties and Fifteen-Forties being effected,—and the provision for the payment of interest at the money-centres and in the moneys of Europe stricken out. Some of its more objectionable features being thus removed, he gave it a qualified support. March 10th, the question being on striking out a provision in the bill of the Committee requiring the national banks to exchange the bonds of the United
  • 76. States deposited by them as security for their circulation for those bearing a lower rate of interest, Mr. Sumner said:— Mr. President,—There is a word which has been introduced into this debate with which we were all very familiar in another relation some years ago. It is the word Coercion. A President of the United States announced in most formal phrase that we could not coerce a State; and now, borrowing a phrase from Mr. Buchanan, we are told we cannot coerce a national bank. Well, Sir, is the phrase applicable? If it be applicable, then I insist that we can coerce a national bank; but I do not admit its applicability. What I insist on has already been so ably and clearly stated by the Chairman of the Committee [Mr. Sherman] that perhaps I need not add another word. I do not like to occupy your time; yet I cannot forbear reminding you, Sir, of the plenary power which Congress has reserved over the banking system in that very Act by which it was established.[224] The Senator from California [Mr. Casserly] has read to you the clause. We have been reminded to-day by a Senator on this floor that these are formal words, words that often appear in statutes. But are they not significant words? Have they not a meaning? Why are they there? Because they have a meaning; because they reserve to Congress what I call plenary power over the whole system. That system may be readjusted, modified, shaped anew, and the banks cannot complain. They began their existence under that law; they knew the conditions of their being; and they cannot now murmur, if Congress chooses to exercise the prerogative which it reserved at the very inception of the whole system. Sir, I approach this question, therefore, with the conviction that the whole matter is open to our discretion. Nobody can say safely that what is now proposed is not within the power of Congress. Congress may do it, if the occasion justifies, if in its discretion it thinks best to do it. It may do it, if it thinks that the financial policy of this country will be thereby promoted. The banks are all parties to that policy. May not the country turn around and ask the banks to do their part in this great work of renovation? To a certain extent the
  • 77. banks are in partnership with the Government. May not the Government insist that they shall do their part on this great occasion? Shall this effort of ours to readjust our finances and to save this large interest to our country be thwarted by a pretension on the part of the banks that we have not the power to interfere? But we are reminded that there is a difference between power and right. How often, Sir, on other occasions, have I so insisted in this Chamber! A great, broad, vital distinction there always is between power and right. A nation or an individual may have a power without right. Now is there not here a right as well as a power? I cannot doubt it. I cannot doubt that Congress may rightfully exercise what I cannot doubt is an existing power. Why should it not? It could exercise it—who can doubt?—with reference to the public interests, to promote the national credit. It will not exercise it in any spirit of wantonness, in any spirit of injustice,—but to promote the national credit. Is not that a rightful object? No one will say the contrary. Why, then, shall we hesitate? We are reminded that these banks have secured certain privileges, and it is said often that those are vested, and the old phrase “vested rights” has been repeated. But how can they have vested rights under a statute which contains the provision just read to us, securing to Congress full power to change it in every respect? What, then, is the simple aspect of this question? It is that certain securities have been lodged with the Government by these banks on which they transact their business, and now in readjusting the national debt it is deemed advisable and for the public interests that the securities should be at a lower rate of interest than when they were originally deposited. Is it not right for Congress to require that? I cannot see the wrong in it. I cannot see any doubt on the question. To my mind it is clear; it is absolutely within the province of Congress, in the exercise of the discretion which it originally retained over this whole subject. I hope, therefore, that in this debate we shall not be pressed too much with the suggestion that we cannot coerce these banks. If the
  • 78. occasion requires, and if the term be applicable, then do I say we may coerce these banks to the extent of obliging them to take these securities at a reduced rate of interest. I find no Repudiation in that. I find nothing wrong in that. I find nothing in it but a simple measure in harmony with this great process of Financial Reconstruction in which we are now engaged. I call it Financial Reconstruction; and in this work ought not the banks to take their place and perform their part? Now, Sir, I have a criticism on this section. It does not go far enough. The Committee propose that the banks shall take one third of the three different kinds of bonds, the five, the four and a half, and the four per cents. I think they ought to be required to take all in fours, and I propose to give the Senate an opportunity of expressing its judgment on that proposition. I may be voted down; perhaps I shall be; but I shall make a motion, in the honest endeavor to render this bill a practical measure, which can best succeed. I wish to mature it; I wish to put it in the best shape possible; and for the sake of the banks, and in the interest of the banks, I wish such a measure as shall have a reasonable chance of stability in the future. If you allow the banks gains that are too large, there will necessarily be a constant opposition, growing and developing as their gains become more conspicuous. Why expose the system to any such criticism? Let us now revise it carefully, place it on sure, but moderate foundations, so that it will have in itself the elements of future stability. To my mind that is the more politic course, and I am sure it is not unjust. You and I, Mr. President, remember very well what was done on another occasion. The State banks were taxed out of existence. It was the cry, “Tax them out of existence! do not let them live! drive them from competition with these new children of ours, the national banks!” It was done. Was not that coercion? If the phrase is to be employed, there was an occasion for it. But I am not aware that it
  • 79. was argued, certainly it was with no great confidence argued, that to do that was unjust. It was a measure of policy wisely adopted at the time, and which we all now see has answered well. But if we could tax the State banks out of existence, can we not, under the very specific terms of the Act of Congress to which these national banks owe their existence, apply a rule not unlike to them? We do not propose to tax them out of existence, but we propose to require that they shall lodge with the Government securities at a lower rate of interest. Something has been said, perhaps much, in this debate, with regard to the burden that this will impose upon the banks. The Senator from Ohio [Mr. Sherman] has already answered that objection, and I do not know that I can add to his answer; and yet I am not aware that he reminded the Senate that in this very bill there is a new and important provision in favor of the banks, or in favor of all bondholders,—being an exemption from all taxation, not only State and municipal, but national. There is but one other remark I will make, and that is, we all know, unless I am much deceived, that the banks have during these last years made great profits. I am told that the profits of the national banks are two or three times greater than those of the old State banks, which we did not hesitate to tax out of existence. Now is not that a fact in this case? Is it not an essential element? Should it not be taken into consideration on this occasion? If these national banks are the recipients of such large profits, should we not exercise all the power that belongs to us to compel them to their full contribution to this great measure of Financial Reconstruction? I cannot hesitate in my conclusion. March 11th, Mr. Sumner moved the addition of a section providing for the resumption of specie payments,—being the seventh section of the original bill,— remarking:— Mr. President,—Interested as I am in this bill, desirous of its passage hardly less than the Senator from Ohio, I am bound to say, that, in my judgment, the passage of this single section would be
  • 80. worth more than the whole bill. It would do more for the credit of the country; it would do more for its business. It would help us all to the completion of Financial Reconstruction. How often have I insisted that all our efforts to fund and refund are to a certain extent vain and impotent, unless we begin by specie payments! That, Sir, is the Alpha of this whole subject; and until Congress is ready to begin with that, I fear that all the rest will be of little avail. It is in the light of expedient rather than of remedy. There is the remedy. The proposition was negatived,—Congress not being yet ready for this step.
  • 81. M MAJOR-GENERAL NATHANAEL GREENE, OF THE REVOLUTION. Speech in the Senate, on the Presentation of his Statue, January 20, 1870. In the Senate, January 20, 1870, Senator Anthony announced the presentation by Rhode Island of a statue of Major-General Nathanael Greene, of the Revolution, executed by the sculptor Brown, to be placed in the old Hall of the House of Representatives. Mr. Sumner moved its acceptance by the following Concurrent Resolution:— A Resolution accepting the Statue of Major-General Greene. Resolved by the Senate, the House of Representatives concurring, That the thanks of this Congress be presented to the Governor, and through him to the people, of the State of Rhode Island and Providence Plantations, for the statue of Major-General Greene, whose name is so honorably identified with our Revolutionary history; that this work of art is accepted in the name of the nation, and assigned a place in the old Hall of the House of Representatives, already set aside by Act of Congress for the statues of eminent citizens; and that a copy of this Resolution, signed by the President of the Senate and the Speaker of the House of Representatives, be transmitted to the Governor of the State of Rhode Island and Providence Plantations. On this he spoke as follows:— R. PRESIDENT,—How brief is life! how long is art! Nathanael Greene died at the age of forty-four, and now Congress receives his marble statue, destined to endure until this Capitol crumbles to dust. But art lends its longevity only to lives extended by deeds. Therefore is the present an attestation of the fame that has been won.
  • 82. Beyond his own deserts, Greene was fortunate during life in the praise of Washington, who wrote of “the singular abilities which that officer possesses,”[225] —and then again fortunate after death in the praise of Hamilton, whose remarkable tribute is no ordinary record. [226] He has been fortunate since in his biographer, whose work promises to be classical in our literature.[227] And now he is fortunate again in a statue, which, while taking an honorable place in American art, is the first to be received in our Pantheon. Such are the honors of patriot service. Among the generals of the Revolution Greene was next after Washington. His campaign at the South showed military genius of no common order. He saved the South. Had he lived to take part in the National Government, his character and judgment must have secured for him an eminent post of service. Unlike his two great associates, Washington and Hamilton, his life was confined to war; but the capacities he manifested in command gave assurance that he would have excelled in civil life. His resources in the field would have been the same in the council chamber. Of Quaker extraction, Greene was originally a Quaker. The Quaker became a soldier and commander of armies. Such was the requirement of the epoch. Should a soldier and commander of armies in our day accept ideas which enter into the life of the Quaker, the change would only be in harmony with those principles which must soon prevail, ordaining peace and good-will among men. Looking at his statue, with military coat and with sword in hand, I seem to see his early garb beneath. The Quaker general could never have been other than the friend of peace. Standing always in that beautiful Hall, the statue will be a perpetual, though silent orator. The marble will speak; nor is it difficult to divine the lesson it must teach. He lived for his country, and his whole country,—nothing less. Born in the North, he died in the South, which he had made his home. The grateful South honored him as the North had already done. His life exhibits the beauty and the reward of patriotism. How can his marble speak
  • 83. except for country in all its parts and at all points of the compass? It was for the whole country that he drew his sword of “ice-brook temper.” So also for the whole country was the sword drawn in these latter days. And yet there was a difference between the two occasions easy to state. Our country’s cause for which Greene contended was National Independence. Our country’s cause recently triumphant in bloodiest war was Liberty and Equality, the declared heritage of all mankind. The first war was for separation from the mother country, according to the terms of the Declaration, “That these United Colonies are and of right ought to be Free and Independent States,”—the object being elevated by the great principles announced. The second war was for the establishment of these great principles, without which republican government is a name and nothing more. But both were for country. The larger masses, with the larger scale of military operations, in the latter may eclipse the earlier; and it is impossible not to see that a war for Liberty and Equality, making the promises of the Declaration a reality, and giving to mankind an irresistible example, is loftier in character than a war for separation. If hereafter Greene finds rivals near his statue, they will be those who represented our country’s cause in its later peril and its larger triumph. Just in proportion as ideas are involved is conflict elevated, especially if those ideas concern the Equal Rights of All. Greene died at the South, and nobody knows the place of his burial. He lies without epitaph or tombstone. To-day a grateful country writes his epitaph and gives him a monument in the Capitol.
  • 84. PERSONAL RECORD ON RECONSTRUCTION WITH COLORED SUFFRAGE. Remarks in the Senate, January 21 and February 10, 1870. The arraignment of Mr. Sumner by Mr. Trumbull, of Illinois, in the closing debate on the Virginia Bill, January 21st, included, as remarked in that connection,[228] a reference to matters of earlier date,—specifically among these being the Reconstruction Act of March 2, 1867, conferring upon the colored people of the Rebel States equality of suffrage with the whites.[229] Adverting to the fact that this bill was an amendment in the nature of a substitute for one from the House, and then reading the names of the Senators who voted for it, Mr. Trumbull asked, — “Mr. President, do you miss the name of any Senator from that list of Yeas?—That was the vote by which that amendment was adopted.—The ‘Absent’ were, among others, ‘Mr. Sumner.’” And upon this showing, Mr. Trumbull concluded, that, “Unfortunately the colored citizens of the South have nothing to thank the Senator from Massachusetts for, in having the right of suffrage conferred upon them.” Mr. Trumbull continued:— “Mr. President, this was not the only vote. A vote was taken, after this amendment was adopted, upon the passage of the bill thus amended; and the vote on the passage of the bill was Yeas 29, Nays 10, and among those Yeas is not found the name of the Senator from Massachusetts. “But, Sir, it sometimes happens that malice and hatred will produce results which reason and good-will can never accomplish; and when we passed this bill giving the right of suffrage to the colored men in the South without the aid of the Senator from
  • 85. T Massachusetts and sent it to the President [Mr. Johnson] he vetoed it, and on the question of passing it over his veto the Senator from Massachusetts voted with us. His affection for the President was not such as to allow him to coincide with him in anything. So we got his vote at last, but we had two-thirds without him. “This is the record, Mr. President.” Mr. Sumner answered:— his assault to-day compels me to make a statement now which I never supposed I should be called to make. I make it now with hesitation, but rather to show the Senator’s course than my own. Sir, I am the author of the provision in that Act conferring suffrage; and when I brought it forward, the Senator from Illinois was one of my opponents,—then as now. Senators who were here at that time remember well that this whole subject was practically taken for the time from the jurisdiction of the Senate into a caucus of the Republican party, where a committee was created to whom all pending measures of Reconstruction were referred. I had the honor of being a member of that committee. So was the Senator from Illinois. So was my friend from Michigan [Mr. Howard]. The Senator from Ohio [Mr. Sherman] was our chairman. In that committee this Reconstruction Bill was debated and matured sentence by sentence, word for word; and then and there, in that committee, I moved that we should require the suffrage of all persons, without distinction of color, in the organization of new governments, and in all the constitutions to be made. In making this proposition at that time I only followed the proposition I had made in the Senate two years before,[230] which I had urged upon the people in an elaborate address at a political convention in Massachusetts,[231] which I had again upheld in an elaborate effort for two days in this Chamber,[232] and which from the beginning I had never lost from my mind or heart. It was natural that I should press it in committee; but I was overruled,—the Senator opposing me with his accustomed determination. I was
  • 86. voted down. The chairman observed my discontent and said, “You can renew your motion in caucus.” I did so, stating that I had been voted down in committee, but that I appealed from the committee to the caucus. My colleague [Mr. Wilson], who sits before me, called out, “Do so”; and then rising, said, in language which he will pardon me for quoting, but which will do him honor always, “The report of the committee will leave a great question open to debate on every square mile of the South. We must close that question up.” Another Senator, who is not now here,—I can therefore name him,—Mr. Gratz Brown [of Missouri], cried out most earnestly, “Push it to a vote; we will stand by you.” I needed no such encouragement, for my determination was fixed. There sat the Senator from Illinois, sullen in his accustomed opposition. I pushed it to a vote, and it was carried by only two majority, Senators rising to be counted. My colleague, in his joy on the occasion, exclaimed, “This is the greatest vote that has been taken on this continent!” He felt, I felt, we all felt, that the question of the suffrage was then and there secured. By that vote the committee was directed to make it a part of Reconstruction. This was done, and the measure thus amended was reported by the Senator from Ohio as chairman of the committee. I am compelled to this statement by the assault of the Senator. I had no disposition to make it. I do not claim anything for myself. I did nothing but my duty. Had I done less, I should have been faithless,—I should have been where the Senator from Illinois placed himself. The Senator read from the “Globe” the vote on the passage of the bill, and exulted because my name was not there. Sir, is there any Senator in this Chamber whose name will be found oftener on the yeas and nays than my own? Is there any Senator in this Chamber who is away from his seat less than I am? There was a reason for my absence on that occasion. I left this Chamber at midnight, fatigued, not well, knowing that the great cause was assured, notwithstanding the opposition of the Senator from Illinois,— knowing that at last the right of the colored people to suffrage was
  • 87. recognized. I had seen it placed in the bill reported from the committee. There it was on my motion, safe against the assaults of the Senator from Illinois. Why should I, fatigued, and not well, remain till morning to swell the large and ascertained majority which it was destined to receive?[233] I have no occasion to make up any such record. You know my fidelity to this cause. You know if I am in the habit of avoiding the responsibilities of my position. I cannot disguise, also, that there was another influence on my mind. Reconstruction, even with the suffrage, was defective. More was needed. There should have been a system of public schools, greater protection to the freedmen, and more security against the Rebels, all of which I sought in vain to obtain in committee, and I found all effort in the Senate foreclosed by our action in caucus. Pained by this failure, and feeling that there was nothing more for me to do, after midnight I withdrew. On the return of the Act to the Senate on the veto of the President, I recorded my vote in its favor. What Mr. Trumbull calls “the record” in this case, and which Mr. Sumner, in the surprise of the occasion, seemingly accepts, according to the obvious import of the term, as substantially the complete record, inspection of either the Congressional Globe or the Senate Journal shows to be very far from complete. The vote following the Presidential veto was by no means the only one in which Mr. Sumner’s name appears: between this and the vote which would seem from the representation to have next preceded, designated as “the vote on the passage of the bill,” there intervened another, involving in an important degree the character and fate of the whole measure. The bill in its original form, as it came from the House, was purely, as indicated by its title, “a bill to provide for the more efficient government of the insurrectionary States,” dividing them into military districts and placing them under military rule,—this being deemed the only effectual means of suppressing the outrages continually perpetrated upon the loyalists of the South, black and white, —its Reconstruction features, which included the provision for colored suffrage, being engrafted upon it by the Senate, coupled with considerable modifications of its military details. It was on the votes at this stage, February 16th, that Mr. Sumner’s name was wanting. On the return of the bill to the House for concurrence in these amendments, it at once encountered on the Republican side severe animadversion, aptly expressed in the remark,—“We sent to the Senate a proposition to meet the
  • 88. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com