Using PyCharm scratch files with Django

Scratches are a great feature in PyCharm that are going to speed up your development and prototyping once you start using them. A scratch file is nothing more than a temporary file that lives outside of your regular project structure:

PyCharm scratch files in Project view

While the Django shell is great for trying out your code, it is not that comfortable to work with when you are writing large amounts of code. This is where scratch files comes handy, allowing you to use a regular file but without cluttering up your real codebase.

Though if you fire up a new scratch file and try to access any part of a Django app, for example a model, you are going to get an ImproperlyConfigured-error similar to this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Traceback (most recent call last):
  File "/Users/andreasbergstrom/Library/Preferences/PyCharm2019.1/scratches/scratch_1.py", line 3, in <module>
    from app.models import Job
  File "/Users/andreasbergstrom/Projects/kodare_se/app/models.py", line 5, in <module>
    class BaseModel(models.Model):
  File "/Users/andreasbergstrom/Projects/kodare_se/venv/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/Users/andreasbergstrom/Projects/kodare_se/venv/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config
    self.check_apps_ready()
  File "/Users/andreasbergstrom/Projects/kodare_se/venv/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready
    settings.INSTALLED_APPS
  File "/Users/andreasbergstrom/Projects/kodare_se/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
    self._setup(name)
  File "/Users/andreasbergstrom/Projects/kodare_se/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
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.

The reason is that you are trying to use a Django app that has not been initialized yet. Even if you are just trying to use some model the framework still need to initialize and configure itself. To do this, just drop these lines of code at the top of your scratch file (before any other imports) and replace “YOUAPPNAME” with your app name:

1
2
3
4
5
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "YOUAPPNAME.settings")

import django
django.setup()

Now Django is configured and can be used as expected.