Config pytest-django and pre-commit in Django project

I have a Django project with the following construction:

.
├── db.sqlite3
├── manage.py
├── switch
│   ├── __init__.py
│   ├── settings.py
├── store
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── tests
|   |   ├── __init__.py
|   |   ├── tests.py
│   ├── apps.py
│   ├── migrations
│   ├── urls.py
│   └── views.py
├── .pre-commit-config.yaml
└── pytest.ini

My author is test.ini:

[pytest]
DJANGO_SETTINGS_MODULE = store.settings
python_files = tests.py tests_*.py *_tests.py

The pre-commit file.yaml:

exclude: "^docs/|/migrations/"
default_stages: [commit]

repos:
  - repo: local
    hooks:
      - id: pytest-check
        name: pytest-check
        entry: pytest
        language: system
        pass_filenames: false
        always_run: true

When running tests locally pytest, everything works without errors. When running pre-commit locally pre-commit run --color=always --all-files, everything works without errors.

When I try to commit, I get an error: 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.

If add a forced installation of an environment variable in the test file with the path to the settings file and call django.config(), then the problem is solved.

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")

django.setup()

But I think this is the wrong way and there is another more optimal solution. Please help me. Thanks

Back to Top