Configuring PyCharm settings
In PyCharm, you can configure the settings on two levels: the project level and globally .

Global settings apply to all projects that you open with a specific installation or version of PyCharm. Such settings include IDE appearance (themes, color schemes, menus and toolbars), notification settings, the set of the installed and enabled plugins, debugger settings, code completion, and so on.
Project settings apply to the current project only, unless you configure them as default settings for new projects . Such settings include VCS configuration, code style options, the list of language inspections, and so on.
To configure your IDE, select PyCharm | Settings for macOS or File | Settings for Windows and Linux. Alternatively, press Control+Alt+S or click on the toolbar.
Settings that are NOT marked with the icon in the Settings dialog are global and apply to all existing projects of the current PyCharm version.

Restore IDE settings
When you restore the default IDE settings, PyCharm backs up your configuration to another directory. You can always restore your settings from that backup.
Back up your settings and restore the defaults

- Go to File | Manage IDE Settings | Restore Default Settings . Alternatively, press Shift twice and type Restore default settings .
- Click Restore and Restart . The IDE will be restarted with the default configuration.
When PyCharm restores the default IDE settings, it creates a backup directory with your configuration in:
Run/debug configurations
PyCharm uses run/debug configurations to run, debug, and test your code. Each configuration is a named set of startup properties that define what to execute and what parameters and environment should be used.
With different startup properties, you can define different ways that PyCharm uses to execute your script. For example, you can execute the same code with different Python interpreters, providing various sets of environment variables, and getting input values from alternative files.
There are two types of run/debug configurations:
- Temporary — created every time you run or debug functions or tests.
- Permanent — created explicitly from a template or by saving a temporary configuration. Permanent configurations remain as part of your project until you remove them.
So whenever you run/debug or test your code, PyCharm either uses an existing permanent run/debug configuration or creates a new temporary one.
Permanent configurations have opaque icons while the icons of temporary configurations are semi-transparent.
The maximum number of temporary configurations is 5. The older ones are automatically deleted when new ones are added. If necessary, you can increase this limit in Settings | Advanced Settings | Run/Debug | Temporary configurations limit .
Create permanent run/debug configurations
PyCharm provides the following ways to create a permanent run/debug configuration:
- Save a temporary run/debug configuration as permanent.
- Create from a template or copy an existing configuration.
Save a temporary configuration as permanent
- Select a temporary configuration in the run/debug configuration switcher, click / , and select Save Configuration . Once you save a temporary configuration, it becomes permanent and it is recorded in a separate XML file in the /.idea/ directory. For example, MyProject/.idea/Car.xml .
- Alternatively, select a temporary configuration in the Run/debug configurations dialog and click on the toolbar.
PyCharm provides run/debug configuration templates for different languages, tools, and frameworks. The list of available templates varies depending on the installed and enabled plugins.
Create a run/debug configuration from a template
- Go to Run | Edit Configurations . Alternatively, click in the Run widget and select Edit Configurations from the drop-down menu.

- In the Run/Debug Configuration dialog, click on the toolbar or press Alt+Insert . The list shows the run/debug configuration templates. Select Python .

- Specify the run/debug configuration name in the Name field. This name will be shown in the list of the available run/debug configurations.

- Configure the run/debug configuration parameters. The list of mandatory and optional parameters may vary depending on the selected run/debug configuration type. Some optional parameters are hidden. To view and enable them, click the Modify options link.
For the detailed description of the Python template, see Run/Debug configuration parameters. - You can either run the configuration right away, or save the configuration to run it later.
- Click OK to save the run configuration for later and close the dialog.
- To run the configuration right away, click Run .
Add a macro to a Python run/debug configuration
- Go to Run | Edit Configurations . Alternatively, click in the Run widget and select Edit Configurations from the drop-down menu.

- In the Run/Debug Configurations dialog, select the target configuration from the list of the Python run/debug configurations.
- Click Insert Macros in one of the following fields:
- Script path
- Parameters
- Working directory
- Select a macro from the list of the available macros.

- Click Insert to add the selected macro. See Pass parameters to the running script for an example of using a macro in a run/debug configuration.
Share run/debug configurations
If you are working in a team, you might want to share your run/debug configurations so that your teammates could run the application using the same configuration or enable them to remotely attach to the process you are running.
For these purposes, PyCharm provides a mechanism to store your run/debug configurations as project files and share them through VCS. The same mechanism can also be used when you want to send your configuration as a file to someone else. This saves a lot of time as run/debug configurations sometimes get sophisticated, and keeping them in sync manually would be tedious and error-prone.
Legacy .ipr -based projects do not support individual run/debug configurations. With legacy projects, you can only share all configurations at once by adding the .ipr file to the VCS.

- Go to Run | Edit Configurations . Alternatively, click in the Run widget and select Edit Configurations from the drop-down menu.
- Select the run/debug configuration you want to share, enable the Store as project file option, and specify the location where the configuration file will be stored. If compatibility with PyCharm 2019.3 and earlier is required, store the file in the default location.
- (Optional) If the .idea directory is added to VCS ignored files, the .idea/runConfigurations subfolder will be ignored, too. If you use Git for your project, you can share .idea/runConfigurations only and leave .idea ignored by modifying .gitignore as follows:
/.idea/* !/.idea/runConfigurations
Turning on the Store as project file option does not submit anything to the VCS for you. For run/debug configurations to make their way to a shared repository, you have to check them in like other versioned files.
Run/debug configuration templates
All run/debug configurations are based on templates, which implement the startup logic, define the list of parameters and their default values. The list of available templates is predefined in the installation and can only be extended via plugins. However, you can edit default parameter values in each template to streamline the setup of new run/debug configurations.
Changing the default values of a template does not affect already existing run/debug configurations.
Do not set up a working directory for the default Run/Debug Configurations listed under the Templates node. This may lead to unresolved targets in newly created Run/Debug Configurations.
Configure the default values for a template
- Go to Run | Edit Configurations . Alternatively, click in the Run widget and select Edit Configurations from the drop-down menu.

- In the left-hand pane of the run/debug configuration dialog, click Edit configuration templates… .

- In the Run/Debug Configuration Templates dialog that opens, select a configuration type.

- Specify the desired default parameters and click OK to save the template.
Run/debug configuration folders
When there are many run/debug configurations of the same type, you can group them in folders, so they become easier to distinguish visually.
Once grouped, the run/debug configurations appear in the list under the corresponding folders.

Create a folder for run/debug configurations
- Go to Run | Edit Configurations . Alternatively, click in the Run widget and select Edit Configurations from the drop-down menu.

- In the Run/Debug Configurations dialog, select a configuration type and click on the toolbar. A new empty folder for the selected type is created.

- Specify the folder name in the text field to the right or accept the default name.
- Select the desired run/debug configurations and move them under the target folder.
- Apply the changes. If a folder is empty, it will not be saved.
When you no longer need a folder, you can delete it Delete . The run/debug configurations grouped under this folder will be moved under the root of the corresponding run/debug configuration type.
Run/Debug configurations in the Services tool window
You can manage multiple run/debug configurations in the Services tool window. For example, you can start, pause, and stop several applications, track their status, and examine application-specific details.
Add Run/Debug configurations to the Services window

- Select View | Tool Windows | Services from the main menu or press Alt+8 .
- In the Services tool window, click Add service , then select Run Configuration Type… .
- Select a run/debug configuration type from the list to add all configurations of this type to the window. Note that the tool window will only display the configuration types for which you have created one or more configurations.
Run/Debug configuration parameters
Script path/Module name
Click the list to select a type of target to run. Then, in the corresponding field, specify the path to the Python script or the module name to be executed.
You can use path variables in this field.
In this field, specify parameters to be passed to the Python script.
When specifying the script parameters, follow these rules:
- Use spaces to separate individual script parameters.
- Script parameters containing spaces should be delimited with double quotes, for example, some» «param or «some param» .
- If script parameter includes double quotes, escape the double quotes with backslashes, for example:
-s»main.snap_source_dirs=[\»pcomponents/src/main/python\»]» -s»http.cc_port=8189″ -s»backdoor.port=9189″ -s»main.metadata=»\"location\":>
In this field you can add a macros to pass various project- or context-specific values when running a run/debug configuration. Click + and select one of the available macros from the list. See Adding macros to run/debug configuration for more details.
Allow multiple instances
Select this option if you want to allow multiple instances of the configuration to run at the same time. If this option is disabled, attempting to re-run the configuration will terminate the active session.
Click this list to select one of the projects, opened in the same PyCharm window, where this run/debug configuration should be used. If there is only one open project, this field is not displayed.
This field shows the list of environment variables. If the list contains several variables, they are delimited with semicolons.
By default, the field contains the variable PYTHONUNBUFFERED set to 1. To fill in the list, click the browse button, or press Shift+Enter and specify the desired set of environment variables in the Environment Variables dialog.
To create a new variable, click , and type the desired name and value.
You might want to populate the list with the variables stored as a series of records in a text file, for example:
Variable1 = Value1 Variable2 = Value2
Just copy the list of variables from the text file and click Paste () in the Environmental Variables dialog. The variables will be added to the table. Click Ok to complete the task. At any time, you can select all variables in the Environment Variables dialog, click Copy , and paste them into a text file.
Paths to «.env» files
This field shows paths to .env files with environment variables. If there are several files, the paths to them are delimited with semicolons.
To manage the list of .env files, click Choose «.env» file . In the Environment Files dialog that opens, use Add and Remove to add and remove files.
You can also use and to change the order in which .env files are loaded.
Select one of the pre-configured Python interpreters from the list.
When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.
In this field, specify the command-line options to be passed to the interpreter. If necessary, click , and type the string in the editor.
Specify a directory to be used by the running task.
- When a default run/debug configuration is created by the keyboard shortcut Control+Shift+F10 , or by choosing Run from the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.
- When this field is left blank, the bin directory of the PyCharm installation will be used.
You can use path variables in this field.
Add content roots to PYTHONPATH
Select this checkbox to add all content roots of your project to the environment variable PYTHONPATH;
Add source roots to PYTHONPATH
Select this checkbox to add all source roots of your project to the environment variable PYTHONPATH;
Emulate terminal in output console
Enables running your script or module in the output console with the emulated terminal mode. This mode can be helpful for the tasks that cannot be implemented with the standard output console, for example, when your script performs caret return actions ( print(i, flush=True , end=’\r’ ).
Note that emulating terminal in the output console differs from running the Terminal that is a separate tool window used for running system shell commands.
Run with Python console
Enables running your script or module with the Python console.
Redirect input from
Enables redirecting data from a text file to standard input. Use this option if your script requires some input and you want to automatically submit the values instead of typing them in the Run console. To enable redirecting, select the checkbox and specify the path to the target text file.
Docker container settings
This field only appears when a Docker-based remote interpreter is selected for a project..
Click to open the dialog and specify the following settings:
- Publish all ports : Expose all container ports to the host. This corresponds to the option —publish-all .
- Port bindings : Specify the list of port bindings. Similar to using the -p option with docker run .
- Volume bindings : Use this field to specify the bindings between the special folders- volumes and the folders of the computer, where the Docker daemon runs. This corresponds to the -v option. For more information, refer to Managing data in containers.
- Environment variables : Use this field to specify the list of environment variables and their values. This corresponds to the -e option. For more information, refer to ENV (environment variables).
- Run options : Use this field to specify the Docker command-line options.
Click to expand the tables. Click , , or to make up the lists.
This field only appears when a Docker Compose-based remote interpreter is selected.
Commands and options
You can use the following commands of the Docker Compose Command-Line Interface:
up: Builds, creates, starts, and attaches to containers for a service.
- —abort-on-container-exit
- —build
- —exit-code-from SERVICE
- —scale SERVICE=NUM.
- —timeout TIMEOUT
run: Runs a one-time command against a service.
- —entrypoint CMD
- -l, —label KEY=VAL
- —name NAME
- -p, —publish=[]
- —rm
- —service-ports
- —use-aliases
- -u, —user=»»
- -v, —volume=[]
exec: Runs arbitrary commands in your services.
Use this field to preview the complete command string.
For example, the up —build exec —user jetbrains combination in the Commands and options field produces the following output in the preview:
docker compose -f C:\PyCharm-2019.2\Demos\djangodocker-master\docker-compose.yml -f
Set up PyCharm¶
This section will present a quick guide on how to configure PyCharm as a development environment for working on Kedro projects.
Open a new project directory in PyCharm. You will need to add your Project Interpreter, so go to PyCharm | Preferences for macOS or File | Settings for Windows and Linux:

Choose Project Interpreter:

Click the cog on the right-hand side and click Add:

Select Conda Environment:

Choose Existing environment and navigate your way to find your existing environment. If you don’t see your conda environment in the dropdown menu then you need to open a terminal / command prompt with your conda environment activated and run:
# macOS / Linux which python # Windows python -c "import sys; print(sys.executable)"
Paste the interpreter path into the file picker and click OK:

Finally, in the Project Explorer right-click on src and then go to Mark Directory as | Sources Root:

Set up Run configurations¶
PyCharm Run configurations allow you to execute preconfigured scripts rapidly in your IDE with a click of a button. This may be useful for testing, running and packaging your Kedro projects.
Here we will walk you through an example of how to set up Run configuration for the Kedro CLI run command. It is also applicable to other Kedro commands, such as test or install .
Go to Run | Edit Configurations:

Add a new Python Run configuration:

Specify the Run / Debug Configuration name in the Name field, and edit the new Run configuration as follows:
- Pick Module from the dropdown
- Enter kedro in the Module Name field
- Enter run in the Parameters field
- Enter the path of your project directory into the Working directory field
- Pick Emulate terminal in output console from the Modify options dropdown, and then click OK

Emulate terminal in output console enables PyCharm to show rich terminal output .
To execute the Run configuration, select it from the Run / Debug Configurations dropdown in the toolbar (if that toolbar is not visible, you can enable it by going to View > Toolbar). Click the green triangle:

You may also select Run from the toolbar and execute from there.

For other kedro commands, follow same steps but replace run in the Parameters field with the other commands that are to be used (e.g., jupyter , package , registry etc.).
Debugging¶
To debug, simply click the line number in the source where you want execution to break:


Then click the bug button in the toolbar () and execution should stop at the breakpoint:

For more information about debugging with PyCharm take a look at the debugging guide on jetbrains.com.
Advanced: Remote SSH interpreter¶
This section uses features supported in PyCharm Professional Edition only.
Firstly, add an SSH interpreter. Go to Preferences | Project Interpreter as above and proceed to add a new interpreter. Select SSH Interpreter and fill in details of the remote computer:

Click Next and add the SSH password or SSH private key:

Click Next and add the path of the remote interpreter. Assuming a Unix-like OS, this can be found by running which python within the appropriate conda environment on the remote computer.

Click Finish. Go to Run / Debug Configurations to add a Remote Run. Select the remote interpreter that you have just created. For the script path, get the path of the Kedro CLI on the remote computer by running which kedro (macOS / Linux) in the appropriate environment.

Click OK and then select Remote Run from the toolbar and click Run to execute remotely.

Advanced: Docker interpreter¶
This section uses features supported by PyCharm Professional Edition only.
First, add a Docker interpreter. Go to Preferences | Project Interpreter as above and proceed to add a new interpreter. Select Docker Interpreter and then choose the target Docker image:

Click OK and check that the required packages appear:

Click OK and wait for PyCharm to index your new Python interpreter.
Click OK. Go to Run / Debug Configurations to add a Python Run. For the script path, get the path to the Kedro CLI on an instantiated image by running which kedro (macOS / Linux) in a container environment. Specify run as the parameter. Specify your working directory as the directory that contains your Kedro project on your local machine. Optional: Edit the Docker container volume mount setting if it does not match the directory that contains your Kedro project directory.

Click OK and then select your run configuration from the toolbar and click Run to execute.
Configure Python Console¶
You can configure PyCharm’s IPython to load Kedro’s Extension.
Click PyCharm | Preferences for macOS or File | Settings, inside Build, Execution, Deployment and Console, enter the Python Console configuration.
You can append the configuration necessary to use Kedro IPython to the Starting script:
%load_ext kedro.ipython
With this configuration, when you create a Python Console you should be able to use context, session and catalog.

Configuring the Kedro catalog validation schema¶
You can enable the Kedro catalog validation schema in your PyCharm IDE to enable real-time validation, autocompletion and see information about the different fields in your catalog as you write it. To enable this, open a catalog.yml file and you should see “No JSON Schema” in the bottom right corner of your window. Click it and select “Edit Schema Mapping”.

Add a new mapping using the “+” button in the top left of the window and select the name you want for it. Enter this URL https://raw.githubusercontent.com/kedro-org/kedro/develop/static/jsonschema/kedro-catalog-0.18.json in the “Schema URL” field and select “JSON Schema Version 7” in the “Schema version” field.
Add the following file path pattern to the mapping: conf/**/*catalog* .
pycharm run/debug configuration. Примеры конфигураций
Конфигурации бывают нескольких видов. В моей практике распространены две:
- Django server — для запуска самого сайта.
- Python — для выполнения различных скриптов, у меня чаще всего management-команд.
Расмотрим в отдельности.
Запуск Django приложения в PyCharm (Пример конфигурации Django server)

У меня лично этот процесс происходит автоматически, то есть при открытии папки проекта (через меню «File \ Open. «) PyCharm самостоятельно создаёт конфигурацию Django server с необходимыми настройками:
Если у меня открыть настройки, то он будут такими:
Атоматически распознать Django server и проставить настройки помогает структура папок проекта. У меня она выглядит следующим образом:
collect_static — папка, куда собирается вся статика на боевом сервере для раздачи через прокси-сервер (у меня nginx).
email_auth — приложение, кастомная модель пользователя.
env — виртуальное окружение.
media — сюда собираются все файлы загруженные через сайт.
spec — это простое приложение, которе выполняет некоторые функции сайта. У вас оно может по-другому называться.
static — папка со статическими файлами на уровне проекта.
templates — папка с шаблонами на уровне проекта.
Пример manage.py
from os.path import join, exists, abspath, dirname import os import sys import subprocess import shutil PROJECT_ROOT = abspath(dirname(__file__)) REQUIREMENTS = join(PROJECT_ROOT, 'requirements.txt') VE_ROOT = join(PROJECT_ROOT, 'env') def go_to_ve(): # going into ve if not sys.prefix == VE_ROOT: if sys.platform == 'win32': python = join(VE_ROOT, 'Scripts', 'python.exe') else: python = join(VE_ROOT, 'bin', 'python') retcode = subprocess.call([python, __file__] + sys.argv[1:]) sys.exit(retcode) delete_ve = 'del_ve' in sys.argv or 'delete_ve' in sys.argv if delete_ve: if exists(VE_ROOT): print 'Deleting env. ' shutil.rmtree(VE_ROOT) print 'Done.' sys.exit(0) update_ve = 'up_ve' in sys.argv or 'update_ve' in sys.argv if update_ve: # install ve if not exists(VE_ROOT): import virtualenv print 'Creating virtualenv. ' virtualenv.logger = virtualenv.Logger(consumers=[]) virtualenv.create_environment(VE_ROOT, site_packages=False) print 'Done.' go_to_ve() # check requirements import pip pip.main(['install', '-r', REQUIREMENTS]) sys.exit(0) if exists(VE_ROOT): go_to_ve() # print 'Found virtualenv. Entering. ' try: import settings except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory") sys.exit(1) if __name__ == '__main__': if not delete_ve: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Пример settings.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os try: import local_settings except ImportError: import local_settings_sample as local_settings DEBUG = local_settings.DEBUG ROOT_DIR = os.path.dirname(__file__) ADMINS = (('Maltsev Artem', 'admin@vits.pro'), ) EMAIL_HOST = local_settings.EMAIL_HOST EMAIL_PORT = local_settings.EMAIL_PORT EMAIL_HOST_USER = local_settings.EMAIL_HOST_USER EMAIL_HOST_PASSWORD = local_settings.EMAIL_HOST_PASSWORD EMAIL_USE_TLS = getattr(local_settings, 'EMAIL_USE_TLS', False) EMAIL_USE_SSL = getattr(local_settings, 'EMAIL_USE_SSL', False) SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER MANAGERS = ADMINS DATABASES = local_settings.DATABASES TIME_ZONE = 'Asia/Irkutsk' LANGUAGE_CODE = 'ru' LANGUAGES = (('ru', 'Russian'), ) SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True USE_X_FORWARDED_HOST = True MEDIA_ROOT = os.path.join(ROOT_DIR, 'media') MEDIA_URL = "/media/" STATIC_ROOT = os.path.join(ROOT_DIR, 'collect_static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(ROOT_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', 'compressor.finders.CompressorFinder', ) SECRET_KEY = local_settings.SECRET_KEY MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.gzip.GZipMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) TEMPLATES = [ < 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(ROOT_DIR, 'templates'), ], 'OPTIONS': < 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.csrf', 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', 'cms.context_processors.cms_settings', ], 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ]), ]>>, ] ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' INSTALLED_APPS = ( 'djangocms_admin_style', 'admin_tools', 'admin_tools.dashboard', 'django.contrib.auth', 'email_auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.sitemaps', 'djangocms_text_ckeditor', # note this needs to be above the 'cms' entry 'cms', 'treebeard', 'menus', 'sekizai', 'compressor', 'spec', 'sass_processor', ) + PROJECT_APPS SILENCED_SYSTEM_CHECKS = ('auth.E003', 'auth.W004') AUTH_USER_MODEL = 'email_auth.User' CACHES = < 'default': < 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', >, > LOGGING = < 'version': 1, 'disable_existing_loggers': False, 'filters': < 'require_debug_false': < '()': 'django.utils.log.RequireDebugFalse' >>, 'handlers': < 'mail_admins': < 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' >>, 'loggers': < 'django.request': < 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True >> > ALLOWED_HOSTS = getattr(local_settings, 'ALLOWED_HOSTS', ['localhost', ]) TEST_RUNNER = 'django.test.runner.DiscoverRunner' if DEBUG: INTERNAL_IPS = ('127.0.0.1', ) # --- CMS --- CMS_TEMPLATES = ( ('default.html', 'По умолчанию'), ) # --- end CMS ---
Пример рабочего проекта
Для наглядности я подготовил рабочий демонстрационный проект, который вы можете скачать для наглядности:
По идее, загрузив пример проекта с виртуальным окружением, и открыв его через меню «File \ Open. «, PyCharm автоматически определит Django Server конфигурацию и вы сразу сможете запустить проект. Не забудьте только создать базу данных и применить миграции.
Пример простой конфигурации python-скрипта
Передо мной встала задача: написать скрипт оповещения клиентов об скором истечении срока действия услуг. Запуск скрипта должен производиться из консоли для того, чтобы его можно было добавить в cron. Решением этой задачи служит использование management команды.
Скрипт я написал: теперь самое время его протестировать и отладить в случае необходимости. И чтобы это было легче проводить, можно воспользоваться debug-ом в самом PyCharm-е. Для этого нужно добавить необходимую конфигурацию.
Добавить в PyCharm конфигурацию запуска обычного python скрипта достаточно просто: в списке конфигураций выбираем «Edit Configurations. » (на рисунке выделено синим цветом).
Затем щёлкаем по зелёному плюсику (выделено синей рамкой) и выбираем python:
А затем проделываем несколько нехитрых действий:
- Вписываем имя конфигурации в поле «Name». В моём случае client_notifications, и у меня часто имя конфигурации совпадает с именем самого скрипта — так удобно.
- Указываем полный путь до скрипта в «Script». Да, на скриншоте путь начинается с E 🙂 Раньше под виндой сидел, теперь давно уже на Linux-е.
- Пишем параметры скрипта в «Script parameters». Имя файла моего скрипта client_notifications, поэтому его и пишем.
Нажимаем окей и можно дебажить!
Что касается поля «Interpreter options» — там указываются параметры самого интерпретатора python. По сути они вставляются между python и manage.py.
А «Working directory» можно не трогать. В данном случае он ни на что не влияет.
Запуск Django-Shop приложения в PyCharm
Разберём более сложный пример запуска конфигурации: попробуем запустить скаченный с какого-нибудь репозитория (напр., github) проект на Django. В качестве примера выберем Django Shop — платформа для создания интернет-магазина.
Для начала откроем терминал и склонируем проект с github:
git clone https://github.com/awesto/django-shop.git
Далее выполним специфичные команды для запуска Django Shop демо-примера (для каждого проекта свои команды по запуску!):
cd django-shop virtualenv ~/.virtualenvs/django-shop source ~/.virtualenvs/django-shop/bin/activate pip install -e . pip install -r requirements/test_py3.txt pip install Django==1.9.10 npm install # в версиях 0.9.3 и выше, сначала нужно зайти в папку example cd example export DJANGO_SHOP_TUTORIAL=commodity export DJANGO_DEBUG=True ./manage.py initialize_shop_demo ./manage.py compilescss
В общем случае для любого проекта нужно:
- Создать виртуальное окружение командой virtualenv .
- Войти в виртуальное окружение командой source .
- Установить зависимости (чаще всего они перечислены в файле requirements.txt) командой pip install .
Замечание
Другие выше перечисленные команды я не буду объяснять в данной статье, так как, ещё раз повторюсь, для каждого проекта свои команды по подготовке к запуску приложения.
И наконец, запускаем проект:
./manage.py runserver
Если в терминале получилось запустить проект, то переходим к его запуску в PyCharm. Для этого открываем в PyCharm-е наш проект:
Нам важно, чтобы мы смогли просматривать в PyCharm все файлы проекта, склонированного с github, поэтому выбираем корневую папку проекта django-shop .
Теперь нам нужно добавить поддержку Django для приложения. Для этого выбираем в меню: «File \ Settings . «:
В этом окне нужно настроить Django project root . Эту директорию можно выбирать такую, в которой лежит manage.py. После выбора директории вы заметите, что PyCharm сам попытался определить местонахождение manage.py и settings.py. Давайте ему поможем, определив точное месторасположение этих файлов. В случае с Django Shop settings.py лежит в папке myshop, поэтому щёлкаем на значок «Три точки» в соответствующем поле для открытия диалогового окна и находим наш settings.py.
Обратите внимание, что мы также добавили переменную окружения DJANGO_SHOP_TUTORIAL в поле Environment variables . Чуть ниже вы увидите, что переменные окружения также добавляются при создании конфигурации, и для Django Shop переменную DJANGO_SHOP_TUTORIAL нужно задавать в двух местах, потому что этот проект требует обязательного наличия DJANGO_SHOP_TUTORIAL в переменных окружения. А так как запуск management команд через PyCharm (гор. клавиша Ctrl + Alt + R) таких, как makemigrations или migrate , происходит в отдельной конфигурации, поэтому без указания DJANGO_SHOP_TUTORIAL команды не смогут запуститься и выведут такую ошибку django.core.exceptions.ImproperlyConfigured: Environment variable DJANGO_SHOP_TUTORIAL is not set :
Поэтому поставим DJANGO_SHOP_TUTORIAL=commodity .
Теперь проверим правильно ли выбрано виртуальное окружение для проекта. Переходим в Project Interpreter :
Командой virtualenv ~/.virtualenvs/django-shop было установлено виртуальное окружение для проекта, поэтому проверьте, чтобы в поле Project Interpreter путь совпадал: 2.7.6 virtualenv at ~/.virtualenvs/django-shop . Найти этот путь можно щёлкнув на крайнюю справа стрелочку вниз этого поля. Если в списке нет пути до виртуального окружения, то можно его вручную добавить, щёлкнув на значок шестерёнки (правее стрелки влево):
Теперь закрываем окно настроек, и последнее что нам осталось сделать, это добавить конфигурацию запуска проекта. Для этого щёлкаем Edit Configuration :
И, щёкнув на плюсик, выбираем Django Server:
Теперь остаётся заполнить Environment variables по необходимости:
DJANGO_SHOP_TUTORIAL=commodity DJANGO_DEBUG=True DJANGO_SETTINGS_MODULE=myshop.settings
Имейте ввиду, что, если у вас в переменных окружения DJANGO_SETTINGS_MODULE=settings :
или в manage.py записан путь до settings.py неправильным образом:
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
вместо myshop.settings . То возникнет ошибка:
ImportError: No module named settings
Так как в переменных окружения значение переменной DJANGO_SETTINGS_MODULE должно быть равно правильному пути до settings.py. В нашем примере с Django Shop DJANGO_SETTINGS_MODULE=myshop.settings .