0

Edit This post has been edited as I have zeroed in on the issue but I have not yet resolved it.

Hello,

I am having an issue which throws the following error when I go to run tests through pycharm:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

It appears the issue is with pycharm as I just ran ./manage.py test and the tests executed successfully.

Configurations which I have set using pycharm are:

  • Script path:/MainFolder/MainProjects/project1-backend/tests/test_models.py
  • Environment Variables: PYTHONUNBUFFERED=1; DJANGO_SETTINGS_MODULE=project1backend.settings note the folder to which this belongs to, not project1-backend
  • Python interpreter: Python 3.8 (MainFolder) ~/MainFolder/MainProjects/bin/python
  • Working Directory:/Users/myname/MainFolder/MainProjects/project1-backend
  • Add content roots to PYTHONPATH: not selected
  • Add source roots to PYTHONPATH: selected

Project hierarchy edit test file should be __init__.py not __inity__.py my .env file is located in the project1-backend folder. I am operating in a venv to execute ./manage.py test.

#import from Model class
from django.test import SimpleTestCase
from django.db import models

#User model
class User(models.Model):

    email = models.CharField(max_length=256, primary_key=True)
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)

    def __str__(self):
        return self.email # this defaults to the email address


from django.test import TestCase
from app.models import User

class TestModels(TestCase):

    def setUp(self):
      self.user1 = User.objects.create(
          email="m@gmail.com",
          first_name="misha",
          last_name="lee"
      )

    def test_app_user(self):
        self.setUp()
        self.assertTrue(isinstance(self, User)

Edit

     Traceback (most recent call last):
      File "/Users/myname/MainFolder/MainProjects/project1-backend/tests/test_models.py", line 4, in <module>
        from app.models import User
      File "/Users/myname/MainFolder/MainProjects/project1-backend/app/models.py", line 6, in <module>
        class User(models.Model):
      File "/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__
        app_config = apps.get_containing_app_config(module)
      File "/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
        self.check_apps_ready()
      File "/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready
        settings.INSTALLED_APPS
      File "/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__
        self._setup(name)
      File "/Users/myname/MainFolder/MainProjects/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup
        raise ImproperlyConfigured(
    django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Process finished with exit code 1

I have also included

INSTALLED_APPS = [
    'django.contrib.admin',     
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'app.apps.AppConfig'
]

*note I have tried 'app' by itself as well to no avail.

Appreciate the help in advance! Note I have already looked at the PYTHONPATH answers as well as the __init__.py ones and found they didn't help. I do however think it is path related.

I have also looked at this resource: Running Django tests in PyCharm but have found the answer didn't resolve my issue.

MShar
  • 61
  • 5
  • did you add app into INSTALLED_APPS in settings py? – obayhan Oct 09 '20 at 19:42
  • @obayhan I have added 'app' to the bottom of INSTALLED_APPS. Thank you for the quick response. Still giving me the error. I believe it has to do with the paths but I can't figure out where? – MShar Oct 09 '20 at 19:47
  • So you have defined `MainFolder` as your project root (content root) and defined no source roots. This is why `MainFolder/MainProject/project1-backend` is not in sys.path and app cannot be found. This isn't an ideal setup, but to fix it, don't add content root to PYTHONPATH and `mark` project1-backend as source root. –  Oct 09 '20 at 19:59
  • İs there "__init__.py"s in every parent folder tree? – obayhan Oct 09 '20 at 23:12
  • Can you try changing the "from app.models import User" to "from ..app.models import User" (include ".." which would mean previous folder? Or you could try the full path such as "MainProjects.app.models" – Zhivko Zaikov Oct 10 '20 at 07:08
  • @obayhan Ty again for your reply. I have an __init__.py file. in all folders as described above. I do not have one in the project1-backend folder or MainProjects or MainFolder for that matter. – MShar Oct 12 '20 at 19:01
  • @Melvyn Ty as well for your response. I have added the source root as you have stated and revised sys.path with a band-aid fix (added sys.path.remove, I am still trying to figure our how to access/ modify PYTHONPATH). As per the Traceback seems to be finding the app.models, however I am now getting the above error (see edited section above). – MShar Oct 12 '20 at 19:50
  • @ZhivkoZaikov Ty for your response. When I do this I get a "ImportError: attempted relative import with no known parent package". I jumped on Melvyns idea and I believe I am pretty close. Still having issues see edited traceback above. – MShar Oct 12 '20 at 20:01

1 Answers1

0

I was scouring SO for days as I couldn't figure out why when I ran ./manage.py test everything worked and the test executed. It appeared the settings were configured appropriately (i.e. DJANGO_SETTINGS_MODULE). However, when I started looking into the errors, debugging, and finding potential answers, I figured out Pycharm/pytest was not recognizing a setting in the settings.py file (or any for that matter). Even after I had tried adding the environment variables (i.e. DJANGO_SETTINGS_MODULE) by "Edit[ing] Configurations" of the test in PyCharm.

Solution First I removed all prior test configurations by navigating to Run/Debug Configurations in PyCharm and removing the tests with the "-" button in the top left corner (Pycharm Professional 2020.1). I had to utilize a plugin EnvFile which launches before running the test by navigating to PyCharm --> Preferences --> Plugins and searching for EnvFile. I then added the hidden .env file which I used to store all the environment variables.

This then led me to the:

 Error raise AppRegistryNotReady("Apps aren't loaded yet.")
              django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I rectified this issue with the help of Django docs https://docs.djangoproject.com/en/3.0/ref/applications/ and adding Django.setup() to populate the application registry.

Furthermore, as I found there wasn't a lot of documentation on this, pay special attention to the type of test you are using pytest, nosetests, etc. and the import statements which you are using in tangent. In addition, please be conscious about the difference between TestCase and SimpleTestCase as the latter doesn't require access to a database.

MShar
  • 61
  • 5