Debugging Django apps with Eclipse

Yes you can use Eclipse/PyDev as a graphical debugging tool with Python. The trick is to set up your Python environment correctly within Eclipse. When that is done you can harness the power of setting breakpoints and drawing out information of the debugger by stepping through your code.

The path

I use virtualenv when running my Django projects. This way I can set up different Django projects on my development machine and not have them clash when they have different dependencies. I.e. for reise.no I  set up virtualenv like this:

virtualenv /Users/alex/workspace/reise_noENV/

On the command line I go into this virtual environment by issuing

source /Users/alex/workspace/reise_noENV/bin/activate

In Eclipse you'll also need to set up python path to point to this environment.

python-interpreter

After setting up your python environment we can head on over to running tests in debug mode.

Creating a debug runner

Okay, running tests in commandline mode is as easy as doing "python manage.py test". So taking that into regard we'll create a debug runner for Eclipse that does this.

Choose "Run->Debug Configurations" and we'll set up a PyDev Django runner:

pydev-debug-runner

From this screenshot you'll see that we have created a PyDev Django configuration. I'll name it "reise_no test views". Now you can click the "Arguments" tab and fill in "Program arguments" with what you on the command line would enter after "python manage.py". So here we'll enter "test".

Running

You can now run this configuration either via the Debug button you can find on your right in the current dialog. Or you'll find it under the bug icon. Click the small arrow next to the bug and a dropdown list with all your debug configurations should appear.

So add a couple of breakpoints in your code by right-clicking in the margin of the line where you want to break, and run your test via the debug runner. When you hit a breakpoint Eclipse should now go into Debug View.

Debug view

debug-controls

In the Debug View you can now step through your code with the debugger controls. The two controls you'll use the most are

  • Step into (F5): Go one level deeper to see whats going on in there.
  • Step over (F6): Go to the next line.

You'll also have a list of the current variables that are set. Use these to figure out whats wrong with your code.

debug-vars

Okay, thats it. Now get rid of all those print statements you've been so shamefully using and start using the tools at your disposal :)

Be Sociable, Share!

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Comments are closed.