Configuring PyCharm to debug a Django Shell
Quick Debugging in your IDE

Debugging with PyCharm is relatively straightforward when it comes to vanilla Python applications.  Debugging Django applications can be tiny bit trickier, but PyCharm supplies Django developers with a couple tools out of the box to quickly configure a debug configuration for your application:

PyCharm Debug Configuration

This only presents the developer with two options, though, which I find severely lacking.

  1. Run a Django development server with debugger attached
  2. Run your Django tests with debugger attached

Option 1 works if the code you want to debug can be exercised by a web browser, which is fine if you're debugging a view, but what about a management command?  What about an asynchronous task?

Option 2 works if you're willing to run your test suite in order to debug some logic, and it pre-supposes that you've written a test that exercises that logic.  But, if you're not a subscriber to TDD (and many aren't), and you need to debug some code that is still under development, but clearly not functioning, this as also suboptimal.

Given these two options, I usually defer to a less than optimal method of running code in a Django wrapped Python shell.  At least I can simply import the code I'm debugging and execute it directly, at the cost of losing variable watchers, etc.  It would really be nice to have both of these things, wouldn't it?

There's a Non-Obvious Solution in There

It turns out there's a trivial way to accomplish this, that might not be obvious to Django developers who stop at the built-in PyCharm tooling for Django projects, by using a vanilla Python configuration.

Add a new debug configuration of type Python--skip the Django stuff:

PyCharm New Debug Config

Select your script as the "script" option, and simply provide Django's "shell" command as a parameter:

Configured Django Shell

I name this configuration "Django Shell".  And that's it!  Now you can run debug using the Django Shell configuration.  Set some breakpoints, import your code and get straight to debugging super fast!

Django Debug Shell Close

API-based applications are at our core.

Let's Talk

Post Discussion

Let's Talk Solutions Speak with a Consultant