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:

$ ./manage.py runserver
Traceback (most recent call last):
  File "./manage.py", line 16, in <module>
    execute_manager(settings)
  File "/home/tjs/web/bbr/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/home/tjs/web/bbr/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/tjs/web/bbr/django/core/management/__init__.py", line 261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/home/tjs/web/bbr/django/core/management/__init__.py", line 67, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/home/tjs/web/bbr/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/tjs/web/bbr/django/core/management/commands/runserver.py", line 8, in <module>
    from django.core.handlers.wsgi import WSGIHandler
  File "/home/tjs/web/bbr/django/core/handlers/wsgi.py", line 10, in <module>
    from django import http
  File "/home/tjs/web/bbr/django/http/__init__.py", line 122, in <module>
    from django.utils.http import cookie_date
  File "/home/tjs/web/bbr/django/utils/http.py", line 7, in <module>
    from email.Utils import formatdate
  File "/usr/lib/python2.7/email/__init__.py", line 79, in __getattr__
    __import__(self.__name__)
  File "/usr/lib/python2.7/email/utils.py", line 27, in <module>
    import random
  File "/usr/lib/python2.7/random.py", 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.