简体   繁体   English

如何在pycharm中为Django创建一个临时文件

[英]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. 但是Django设置和环境变量不会自动导入。 Is there a way to do that now or this feature is just meant for pure python code testing. 有没有办法现在这样做或者这个功能只适用于纯python代码测试。

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 :-) 感谢@Leistungsabfall,这是一个有效的解决方案:-)

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. 您不需要向sys.path添加任何内容。 This works for Python 3.7+, Django 2.1+ and PyCharm 2019+: 这适用于Python 3.7 +,Django 2.1+和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. 在临时文件的顶部添加它以访问Django应用程序。 Futher info on ImproperlyConfigured-error . 有关ImproperlyConfigured-error的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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