简体   繁体   中英

How to create a scratch file in pycharm for Django

I can create a scratch file from menu "Tools" -> "New Scratch File...".

But Django settings and environment variables are not imported automatically. Is there a way to do that now or this feature is just meant for pure python code testing.

I want to be able to

from website.models import *

but I get this error

File "/Users/user1/.virtualenvs/test-env/lib/python2.7/site-packages/django/conf/__init__.py", line 40, in _setup
% (desc, ENVIRONMENT_VARIABLE))

Thanks

Thanks to @Leistungsabfall, here is a working solution :-)

import os, sys

sys.path.append(os.path.join('/Users/user1/gitroot/website1/web', 'myproject'))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
from django.conf import settings

from website.models import *

You should not need to add anything to sys.path. This works for Python 3.7+, Django 2.1+ and PyCharm 2019+:

import os

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

import django
django.setup()

Add this at the top of your scratch-file to have access to a Django app. Futher info on ImproperlyConfigured-error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM