Book Image

Django JavaScript Integration: AJAX and jQuery

By : Jonathan Hayward
Book Image

Django JavaScript Integration: AJAX and jQuery

By: Jonathan Hayward

Overview of this book

<p>You want to create an AJAX application. Why would you use Django? Why would you use jQuery? Why would you use both together? Enter <i>Django JavaScript Integration: AJAX and jQuery</i> &ndash; 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.</p> <p>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 "<i>The web framework for perfectionists with deadlines</i>", how jQuery &ndash; the "<i>write less do more</i>" JavaScript library &ndash; is practically a virtual higher-level language, and why they both deserve to be integrated with AJAX.</p> <p>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.</p> <p>The first two chapters provide a short and necessary introduction to the world of Django, jQuery, and AJAX; and 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.</p> <p>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".</p> <p>You will cover the basics of AJAX; use jQuery, the commonest JavaScript library, on the client side, and learn form validation with an eye to 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. 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.</p> <p>After working through this book, you will have both an AJAX application and a deep understanding that you can use to customize, extend, and further develop it in your organization.</p> <p>This book has been written and tested for Django v 1.2.3 and jQuery v 1.4.4.</p>
Table of Contents (20 chapters)
Django JavaScript Integration: AJAX and jQuery
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

"Just fiddling with Firebug" is considered harmful


With a tool like Firebug comes a temptation to offload the responsibility from our shoulders to the debugger's. Features like Firebug's console.dir(), which lets you explore an object interactively, can be very powerful. However, they can become a crutch.

Cargo cult debugging at your fingertips

Who is most effective in hand-to-hand combat: someone unskilled who is wielding a sword, someone unskilled wielding a mace, or a good blackbelt who is empty-handed?

Any, or depending on the martial art, all of these people may be more effective with a weapon than without. But weapons do not wield themselves: people, skilled or unskilled, wield them. And as impressive a tool as Firebug is, or Chrome's developer tools, a skilled developer using alert() well can and will debug better than a programmer who hopes that Firebug will provide a way out of the difficult work of understanding hard bugs.

Some people have raised concerns that expensive medical diagnostics make for worse physician diagnoses, not better. The reason for this is that a doctor relying on clinical observation is aware of the need for attentive vigilance in trying to make the best observations from what is available. With testing, there is a new temptation to try and let the test make the diagnosis, and a test that is asked to make a diagnosis is just not as good as a good physician's observation and reasoning. Nobody sets out for this to happen, but it does happen.

In the imagination of popular children's stories, detectives carry around magnifying glasses to look at things. Detectives today use more technology, not less, and can and do make magnified photographs. Perhaps the picturesque magnifying glass is a quaint image, and real police detectives may not use them as well-equipped soldiers do not have quaint flintlock muskets any more. But it is the martial artist, detective, doctor, or developer, who uses the tool. And that means that before we look at how good debugging can use Firebug or Google Chrome's developer tools, we should look at good debugging itself. Only after we have laid a foundation is it appropriate to ornament it with the virtues of good debugging weapons.

The scientific method of debugging

The core of the scientific method is not just something useful for explicitly labeled science. It can be used in several cases. In the scientific method, we do something like the following:

  • Start with something you have observed but you don't understand

  • Then you make hypotheses: educated guesses that might account for the phenomenon

  • Think of an experiment, or experiments, where your hypotheses predict different results

  • Perform the experiment(s) and try to narrow down which hypotheses account for all the data

  • Repeat the cycle as desired

In science, this method is applied to understand how the natural world works. In scientific debugging, we use it to understand how our software does not work: we cannot solve the problem correctly until we understand what the problem is. And in debugging, band-aid solutions are just that: band-aids that leave the root cause unaddressed. The scientific method of debugging is not a tool for finding a band-aid that will mask a problem, but for finding the root cause so we can fix it there. We try first to duplicate a problem, then reproduce it consistently, then pin down when it does and does not happen. This is true whether or not we have debugging tools to use.

Exhausting yourself by barking up the wrong tree

Often when we are having trouble finding a bug, we are looking somewhere the bug cannot be found. You cannot find something by looking twice as hard in the wrong place.

Sometimes, if we listen, we will get subtle, easily overlooked clues that we are barking up the wrong tree. For instance, suppose we have the following code:

function init()
    {
    if (detect_feature())
        {
        initialize_with_feature();
        }
    else
        {
        initialize_without_feature();
        }
    }

And we can't tell which branch of the conditional is being executed. So we add console.log() calls (which work in either Firebug or Chrome):

function init()
    {
    if (detect_feature())
        {
        console.log("init 1");
        initialize_with_feature();
        }
    else
        {
        console.log("init 2");
        initialize_without_feature();
        }
    }

Note

We might suggest a naming convention for console.log() calls of the function's name, and then a space, and then a number or unique identifier for the call, and then any variable or other information which we might want to inspect. This is both easy and makes large amounts of logging material, if we need it, more navigable.

So we run this, and to our consternation nothing shows up in the log: neither init 1 nor init 2 is logged. The temptation is to say that the experiment was a complete failure. But if we are open to a surprise and a bit of serendipity, the experiment was a success: it showed that neither branch was being executed. That could be because init() was not being called at all, or because detect_feature() was hanging and not returning, or throwing an exception that is silenced later on. So to test that, we could add another log line:

function init()
    {
    console.log("init 3");
    if (detect_feature())
        {
        console.log("init 1");
        initialize_with_feature();
        }
    else
        {
        console.log("init 2");
        initialize_without_feature();
        }
    }

And then we have evidence either that init() is not being called, or that it is being called but detect_feature() is not completing, quickly and successfully, and passing control to either branch of the conditional.

The humble debugger

Dijkstra's famous essay The humble programmer talked about how arrogance about one's programming abilities makes for a bad programmer. Humility can help us debug, and not only by letting us accept that our code has defects. Another side of programming humility, on a deeper level, lets us be open to surprises. Humility is an openness that can receive serendipity, and it is an openness that can receive what the code actually has instead of projecting its desires, reading into the code what it wants to see. More concretely, part of humble openness means that when you do something and the program doesn't do what you want, you are open, and choose to be open, to what the program is actually doing. What you avoid is doing the same thing a few more times in the hope that it will work correctly when you know you have seen a bug.

In concrete, this means unplugging a time sink that slowly nickels and dimes away time spent sticking one's head in the sand when we could cut to the chase and start real debugging the first time the bug shows itself, not reluctantly after it refuses to go away and yield to our wishful thinking. If you are looking and looking for a bug and not finding it, the reason may well be that the bug you are looking for doesn't exist anywhere. What you need to do is recognize when you are searching and by accident stumble over a different problem that will let you address the issue. Now part of debugging may involve legitimately doing things again to try to sound out the scope and what triggers a bug. But that does not make it helpful to consent to having our time nickeled and dimed away because we allow ourselves wishful thinking and the tacit hope that maybe the bug will go away without being fixed if only we try again a time or two.

Solving hard bugs is usually a matter of serendipity. It is like trying to find a needle in a haystack, and accidentally discovering that there are valuables that had been hidden in the haystack. It is tripping over the truth but not, pace Winston Churchill, picking yourself up and continuing on.

The value of taking a break

Taking a break can work. Asking an extra set of eyes can work. And pulling an all-nighter is working harder, not smarter: one hour of looking at code with fresh and well-rested eyes is worth a dozen hours of staring at the same code with blurry, sleepy eyes.

If humility matters more than you might think, persistence may be overrated. If you are locked into finding a bug one way, you may do well with a break. A Whack on the Side of the Head by Roger von Oech, Business Plus, available as an iPhone app, may be invaluable (see http://creativethink.com/). Conceptual Blockbusting by James Adams, Perseus is also invaluable. A bit of brainstorming may help you loosen up from being locked into searching where the problem may not be at all. And a bit of exercise can get blood flowing as well as loosening your thoughts.

Two major benefits to asking for help

There are two major benefits to asking for help. The first benefit is that the person you ask might be able to solve the problem. But there is another, less obvious benefit: when you ask another programmer for help, usually you do not just say "My program is not working"; you carefully explain what is going on so the other person has something to go on. And it happens more than you might expect that in the course of explaining what is going on, you realize what is causing the other bug, whether or not your dialogue partner spoke a word. "Confessional debugging" happens all the time.