0

I'm trying to run a Django app on an Ubuntu VM but when I execute python manage.py runserver I get this error message:

ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

The code is de default of a Django project, ie,

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

I've tried with all of the things described in this post (ie, I'm in a venv reciently created with django installed, checked the django installation, verified that PYTHONPATH is pointing to venv/lib/python3.8/site-packages, etc.) but I still have the error. Any idea?

Palinuro
  • 184
  • 1
  • 1
  • 15

2 Answers2

0

Can you run command pip list to check Django is installed? if is installed uninstall pip uninstall Django and then use this command to install again python -c "import django"

and try again with new project

  • With `pip list` I verified that it's installed. After uninstall it, `python -c "import django"` gets an error because Django is not installed. It's not a command for installation. – Palinuro Jul 07 '23 at 19:22
-1

I've tried installing Django with:

sudo python3 -m pip install django

and it worked.

Palinuro
  • 184
  • 1
  • 1
  • 15
  • 2
    You should _never_ run pip with sudo. The official [Python docs package installation tutorial](https://packaging.python.org/en/latest/tutorials/installing-packages/) even warn as much ("Do _not_ run any of the commands in this tutorial with sudo"). If you think you need to use sudo, it's becasue your virtual enviroment isn't set up right. See also [What are the risks of running 'sudo pip'?](https://stackoverflow.com/q/21055859/11082165) – Brian61354270 Jul 07 '23 at 19:51
  • You are right. But which is the alternative? – Palinuro Jul 11 '23 at 21:54
  • Make sure you're using your virtual environment correctly. Verify that your user owns the virtual environment (i.e., you didn't accidentally ownership of it or any files in it to root), and that `python3` references the virtual environment interpreter (`type python3`). Then just `python3 -m pip install django` would work. – Brian61354270 Jul 11 '23 at 23:30