Search code examples
pythondjangopipvirtualenvsudo

How can I configure Django setup to not need sudo?


I have pip, virtualenv, and django installed globally. Using py3, default is set using alias line in ~./bash_profile - so py2 packaged with Mac still there.

In new virtualenv, activated, but when I try to do anything with django get following error:

$ python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named 'django'

If I run with sudo (i.e. sudo python manage.py migrate) command works.

I know problem is likely how I installed pip, but anyway to fix this without re-installing everything?


Solution

  • This can happen for several different reasons (from most basic to more complicated):

    1. Django not installed, either globally, in your virtualenv, or both. Check using pip list. Most of the time pip install django will fix. Do not sudo this, or you will have to sudo everything. Also: double check django version matches python version; pip install --upgrade django to get latest version.
    2. Virtualenv not activated - use source your_path/venv/bin/activate
    3. Mac users - running python3 on virtualenv, but python2.7 default on comp. Fix by deactivating first virtualenv, manually deleting bin||venv, start new virtualenv set to use python2.7. Use virtualenv -p /usr/bin/python2.7 env.
    4. Similar - server running different versions. Sometimes you can fix with alias (ala alias python=python2.7), but make sure to only use on instance being used for project, not on local comp. Local comp wont work, because sudo being run for default python version regardless.
    5. In manage.py defaulted path not correct. This depends on your setup and where python dependencies stored. If this is your problem, replace shebang with #!/usr/bin/env python. Be careful re: python versions here, so if issue with OS default different from using, just add number to end of python (ex: python3).
    6. Follow @antonis answer, figure out where in $PYTHONPATH not matching up with sudo PATH. Pipe/update profile to fix.