Search code examples
djangopycharmdjango-testing

ModuleNotFoundError: No module named 'django', when I run tests


When I run the tests (in the pycharm environment) I get an error ModuleNotFoundError: No module named 'django'. Django installed (2.2.5)

Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "/home/m0nte-cr1st0/projects/slack_bot/tests.py", line 4, in <module>
    from app.models import *
  File "/home/m0nte-cr1st0/projects/slack_bot/app/models.py", line 1, in <module>
    from django.db import models
ModuleNotFoundError: No module named 'django'

Solution

  • You probably have not configured your PyCharm Project to use your virtualenv for tests.

    1. In your Run/Debug configurations (the dropdown next to the run button), select "Edit Configurations".
    2. Find your test configuration and check the value for "Python Interpreter". If should be something like /home/m0nte-cr1st0/.virtualenvs/slack_bot/bin/python, but probably it is something like /usr/bin/python3.6
    3. If it is in the list, select /home/m0nte-cr1st0/.virtualenvs/slack_bot/bin/python. Otherwise, you have to add a new interpreter.

    To add an interpreter, look at the status bar on the bottom right. It should say "Python 3.6". If you click on it, there should be an option to add an interpreter.