Skip to content

Instantly share code, notes, and snippets.

@biwin
Last active January 12, 2024 10:53
Show Gist options
  • Save biwin/8e7ae32e54a8a4cdfa3ee5740bac26dc to your computer and use it in GitHub Desktop.
Save biwin/8e7ae32e54a8a4cdfa3ee5740bac26dc to your computer and use it in GitHub Desktop.
Change PyCharm Community Python Console to PyCharm Professional Django Console (Django Shell)
# Change the run script on `settings> Build Execution and Deployment > Console > Python Console` to
# hoping you have your settings at project/project/settings.py (if not, change accordingly;)
import os,sys,django;sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
os.environ['DJANGO_SETTINGS_MODULE'] = WORKING_DIR_AND_PYTHON_PATHS.split('/')[-1]+'.settings'
print('Python {0} on {1} using {2} as settings'.format(sys.version, sys.platform, os.environ['DJANGO_SETTINGS_MODULE']))
django.setup()
@edi-spaghetti
Copy link

edi-spaghetti commented Jan 16, 2021

Don;t know if this has changed, but in my version of pycharm (2019.1.2) WORKING_DIR_AND_PYTHON_PATHS gets string replaced as a sort of pre-processor operation with a tuple, so that .split() call doesn't work as intended.

As an exmaple, if its value is '/working/dir', '/python/path' then you'll end up with a tuple ('/working/dir', 'path.settings') assigned to that environment variable - which throws an error TypeError: str expected, not tuple.

Also, even if the split and string operation worked as intended, it relies on the project's working directory being that last thing in the list. which is not necessarily the case.

I found it easier just to explicity type in the project name to the console, setting DJANGO_SETTINGS_MODULE to equal '<project_name>.settings'.

Other than that, this works fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment