How to Debug in Django, the Good Way

How to debug in Django, the good way?

There are a bunch of ways to do it, but the most straightforward is to simply
use the Python debugger. Just add following line in to a Django view function:

import pdb; pdb.set_trace()

or

breakpoint()  #from Python3.7

If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.

However there are other options (I am not recommending them):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at IPDB that uses ipython for debugging.

Some more useful extension to pdb are

pdb++, suggested by Antash.

pudb, suggested by PatDuJour.

Using the Python debugger in Django, suggested by Seafangs.

Django - How can I debug code which POST's when a bug seems to be in the view?

Add logging statements to your code. A good place to start is to log the outcome of every decision and the result of every important function call, like so:

def myView(request):

import logging
logging.basicConfig(filename='mylog.log', level=logging.DEBUG)

if request.method == 'POST':
logging.debug('request.method=POST')
form = MyForm(request.POST)
logging.debug('form=%s', form)

if concept_form.is_valid():
logging.debug('form is valid')
myform = form.save()
logging.debug('called form.save(), result=%s', myform)

else:
logging.debug('form is not valid')
else:
logging.debug('request.method is not POST')

how do i debug/breakpoint my django app using pycharm?

So i gave all the answers here a +1 for trying - but they're not the issue. Near as i can tell, the answer is that pycharm is broken. Which is a pain, but the solution is easy -

IF you dont' want to use the little green button at the top of pycharm, or use the pycharm debugging feature? then don't worry, you don't need to do anything. Continue using ctrl-shift-r and runserver (or whatever your shortcut to manage.py is)

IF you do want to use the little green "run" button, or if you want to use pycharm's debugging kit, then you absolutely cannot use the "add_to_builtins", at least in the settings.py file (I never put it anywhere else myself, pycharm might require it elsewhere?). add_to_builtins doesn't work in pycharm - it gets itself caught in a loop of grave consequences when you use the little green button or the debug button. Using ctrl-shift-r and runserver doesn't, curiously, have this problem.

The good news is that "add_to_builtins" isn't a must-have, just a nice-to-have. Just add the "{% load x %}" command to each template where you use x and you will be set.
Alternatively, save a hundred bucks and use some sort of free eclipse tool.

Is there a way to debug Django urls?

You have login required somewhere which sends you to default login page location

If you are going to use default authentication you can add these views up

How to use visual studio code to debug django

For VSCode (full disclosure, I'm one of the VSCode developers) try installing the Python extension to get started.

This documentation covers debugging Django. There should be a included debug configuration or you can add your own to the launch.json file:

{
"name": "Django",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config.python.pythonPath}",
"program": "${workspaceRoot}/manage.py",
"args": [
"runserver",
"--no-color",
"--noreload"
],
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput",
"DjangoDebugging"
]
}

The Python extension also provide many other features that you may find useful.

Hope that helps you get started.

What is the nice way to debug django when requests originate remotely?

What you should do

Debugging should not be done on a production server, so you should use a development server, where you can basically use manage.py runserver+ import pdb; pdb.set_trace().

Why couldn't you do it

Say your dev server is running on a platform like heroku, you might not be able to control how your script is started. From there, using remote-debugging is possible, and here's how you could do it:

What you could do

If you want to be able to step-in code execution and debug remotely (which is totally innapropriate for a production setup), you could use rpdb. I insist on the fact that you shouldn't be doing this unless you know what you're doing (and provided you're not doing it on a production server!)

Basically, what rpdbdoes is that when you call rpdb.set_trace(), pdb is started and its stdinand stdoutare redirected towards port 4444 (but you can change that of course). You'd then telnet (or netcat, for that matter) to that port and do your debugging thing from there.

Closing words

Really, you shouldn't be doing this.

How to run Debug server for Django project in PyCharm Community Edition?

Yes you can.

  1. In Run -> Edit Configurations create new configuration
  2. [+] / Python
  3. Name: runserver
  4. Scrip Path: path_to/manage.py
  5. Parameters: runserver

How can I get Django to print the debug information to the console?

Update - 2016

This post is still getting hits.

I recommend using one of the approaches below that use the built in logging system.

In the same way exceptions are piped to the admin email handler, you can send the data to a console logger, file logger, or anywhere else (solely, or in addition to the email handler.)

Original answer

Well, the easiest way is to set debug mode OFF and let django email you the error, since that literally takes 5 seconds:
http://docs.djangoproject.com/en/dev/howto/error-reporting/

Otherwise, I'd write a middleware that logs the exception, but it's a little more of a pain if you want the stack trace. Here's the documentation.

import traceback
import sys
from __future__ import print_function

class ProcessExceptionMiddleware(object):
def process_exception(self, request, exception):
# Just print the exception object to stdout
print(exception)

# Print the familiar Python-style traceback to stderr
traceback.print_exc()

# Write the traceback to a file or similar
myfile.write(''.join(traceback.format_exception(*sys.exc_info())))


Related Topics



Leave a reply



Submit