django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment varia

Use this

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

instead of

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.settings")

In your python script, you are trying to access Django models before setting the environment try it in this order :

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.`settings`")
from <appname>.models import Class1, Class2,...

If you are using PyCharm Pro, you can either test your app by action 'Run Django Console...'. After you click 'test', it will prompt you for the app you want to test.

enter image description here

or

Create a Django test in Run/Debug configuration.

enter image description here