Django cannot import name urandom

August 14, 2012

I recently tried to spin up a local django server and was confronted with the following error:

$ ./ runserver
Traceback (most recent call last):
  File "./", line 16, in <module>
  File "/home/tjs/web/bbr/django/core/management/", line 438, in execute_manager
  File "/home/tjs/web/bbr/django/core/management/", line 379, in execute
  File "/home/tjs/web/bbr/django/core/management/", line 261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/home/tjs/web/bbr/django/core/management/", line 67, in load_command_class
    module = import_module('' % (app_name, name))
  File "/home/tjs/web/bbr/django/utils/", line 35, in import_module
  File "/home/tjs/web/bbr/django/core/management/commands/", line 8, in <module>
    from django.core.handlers.wsgi import WSGIHandler
  File "/home/tjs/web/bbr/django/core/handlers/", line 10, in <module>
    from django import http
  File "/home/tjs/web/bbr/django/http/", line 122, in <module>
    from django.utils.http import cookie_date
  File "/home/tjs/web/bbr/django/utils/", line 7, in <module>
    from email.Utils import formatdate
  File "/usr/lib/python2.7/email/", line 79, in __getattr__
  File "/usr/lib/python2.7/email/", line 27, in <module>
    import random
  File "/usr/lib/python2.7/", line 47, in <module>
    from os import urandom as _urandom
ImportError: cannot import name urandom

This is caused by attempting to run a python 2.7.2 binary against python 2.7.3 libraries.

To fix this, remove the python symlink from your virtualenv (probably ~/.virtualenvs/ENV_NAME/bin/python) and then regenerate the virtualenv from the command line:

$ mkvirtualenv ENV_NAME
New python executable in ENV_NAME/bin/python
Installing setuptools.............done.
Installing pip...............done.