How Django shows the “It worked!” page?

If you do the following, you will see a “It worked!” page at

$ django-admin.py startproject myproject
$ python manage.py runserver

Let's find out how it is done.

First search the django package to find the phrase “It worked!”. Assuming you are at the root of the django package:

$ grep -ri "it worked!" --include=*.py .
./views/debug.py:  <h1>It worked!</h1>

Look into debug.py and you will see “It worked!” is defined in the string “DEFAULT_URLCONF_TEMPLATE”.

“DEFAULT_URLCONF_TEMPLATE” is used in a module level function “default_urlconf()” in the same file.

The “default_urlconf()” function is called by another module level function “technical_404_response()” in the same file.

Portion of “technical_404_response() is listed below:

        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
        if (not tried # empty URLconf
            or (request.path == '/'
                and len(tried) == 1 # default URLconf
                and len(tried[0]) == 1
                and getattr(tried[0][0], 'app_name', '') == 
                        getattr(tried[0][0], 'namespace', '') == 'admin')):
            return default_urlconf(request)

You can see that it checks for the special case of hitting the root url “/” and filtering out the admin site.

Let's do a search on technical_404_response():

$ grep -ri "technical_404_response" --include=*.py .
./views/debug.py:def technical_404_response(request, exception):
./contrib/staticfiles/handlers.py:   return debug.technical_404_response(request, e)
./core/handlers/base.py:             response = debug.technical_404_response(request, e)

The relevant file is “base.py”. In the definition of class BaseHandler(object) in base.py, if the DEBUG setting is True, then it will call technical_404_response() and eventually returns the “It worked!” page, as illustrated in the code fragment below.

        except http.Http404 as e:
            logger.warning('Not Found: %s', request.path,
                            'status_code': 404,
                            'request': request
            if settings.DEBUG:
                response = debug.technical_404_response(request, e)

No comments: