Как настроить pycharm для django

pycharm run/debug configuration. Примеры конфигураций

12 февраля 2014 г. 3:50

Конфигурации бывают нескольких видов. В моей практике распространены две:

  1. Django server — для запуска самого сайта.
  2. Python — для выполнения различных скриптов, у меня чаще всего management-команд.

Расмотрим в отдельности.

Запуск Django приложения в PyCharm (Пример конфигурации Django server)

У меня лично этот процесс происходит автоматически, то есть при открытии папки проекта (через меню «File \ Open. «) PyCharm самостоятельно создаёт конфигурацию Django server с необходимыми настройками:

Если у меня открыть настройки, то он будут такими:

Атоматически распознать Django server и проставить настройки помогает структура папок проекта. У меня она выглядит следующим образом:

Пример manage.py

Пример settings.py

Пример рабочего проекта

Для наглядности я подготовил рабочий демонстрационный проект, который вы можете скачать для наглядности:

По идее, загрузив пример проекта с виртуальным окружением, и открыв его через меню «File \ Open. «, PyCharm автоматически определит Django Server конфигурацию и вы сразу сможете запустить проект. Не забудьте только создать базу данных и применить миграции.

Пример простой конфигурации python-скрипта

Передо мной встала задача: написать скрипт оповещения клиентов об скором истечении срока действия услуг. Запуск скрипта должен производиться из консоли для того, чтобы его можно было добавить в cron. Решением этой задачи служит использование management команды.

Скрипт я написал: теперь самое время его протестировать и отладить в случае необходимости. И чтобы это было легче проводить, можно воспользоваться debug-ом в самом PyCharm-е. Для этого нужно добавить необходимую конфигурацию.

Добавить в PyCharm конфигурацию запуска обычного python скрипта достаточно просто: в списке конфигураций выбираем «Edit Configurations. » (на рисунке выделено синим цветом).

Затем щёлкаем по зелёному плюсику (выделено синей рамкой) и выбираем python:

А затем проделываем несколько нехитрых действий:

  1. Вписываем имя конфигурации в поле «Name». В моём случае client_notifications, и у меня часто имя конфигурации совпадает с именем самого скрипта — так удобно.
  2. Указываем полный путь до скрипта в «Script». Да, на скриншоте путь начинается с E 🙂 Раньше под виндой сидел, теперь давно уже на Linux-е.
  3. Пишем параметры скрипта в «Script parameters». Имя файла моего скрипта client_notifications, поэтому его и пишем.

Нажимаем окей и можно дебажить!

Что касается поля «Interpreter options» — там указываются параметры самого интерпретатора python. По сути они вставляются между python и manage.py.
А «Working directory» можно не трогать. В данном случае он ни на что не влияет.

Запуск Django-Shop приложения в PyCharm

Разберём более сложный пример запуска конфигурации: попробуем запустить скаченный с какого-нибудь репозитория (напр., github) проект на Django. В качестве примера выберем Django Shop — платформа для создания интернет-магазина.

Для начала откроем терминал и склонируем проект с github:

Далее выполним специфичные команды для запуска Django Shop демо-примера (для каждого проекта свои команды по запуску!):

В общем случае для любого проекта нужно:

  1. Создать виртуальное окружение командой virtualenv .
  2. Войти в виртуальное окружение командой source .
  3. Установить зависимости (чаще всего они перечислены в файле requirements.txt) командой pip install .

И наконец, запускаем проект:

Если в терминале получилось запустить проект, то переходим к его запуску в 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 :

/.virtualenvs/django-shop было установлено виртуальное окружение для проекта, поэтому проверьте, чтобы в поле Project Interpreter путь совпадал: 2.7.6 virtualenv at

/.virtualenvs/django-shop . Найти этот путь можно щёлкнув на крайнюю справа стрелочку вниз этого поля. Если в списке нет пути до виртуального окружения, то можно его вручную добавить, щёлкнув на значок шестерёнки (правее стрелки влево):

Теперь закрываем окно настроек, и последнее что нам осталось сделать, это добавить конфигурацию запуска проекта. Для этого щёлкаем Edit Configuration :

Читайте также:  Можно ли ехать если не работает поворотник

И, щёкнув на плюсик, выбираем Django Server:

Теперь остаётся заполнить Environment variables по необходимости:

Имейте ввиду, что, если у вас в переменных окружения DJANGO_SETTINGS_MODULE=settings :

Источник

Настройка удаленного интерпретатора на Pycharm для Django


В этой статье хочу рассказать, а также показать настройку полезного инструмента для удаленной разработки от компании JetBrains встроенное в IDE Pycharm. Такой инструмент есть уже давно, но многие разработчики относятся к этому не серьезно, и для внесения изменений в проект предпочитают разворачивать его локально. Когда намного легче на том-же сервере, сделать копию части проекта и изменять или тестировать на другом порту с помощью встроенных средств удаленного интерпретатора Pycharm. Конечно не во всех ситуациях это хороший вариант, но для правки, и доработки небольших проектов очень даже подходит. А если проект с нуля, то создавая его на удаленном сервере, исчезает потребность в переносе и адаптации его под сервер(хостинг), которые неизбежно ведут к появлению множества багов и несовместимостей.

К тому же такой подход нас избавляет от таких проблем:

• на разных серверах свой Unix и свои приколы, разворачивать локально и подгонять среду под особенности того или иного сервера может занять приличное количество времени;
• разные версии python;
• И если в файле req.txt для Django не указаны все зависимости;
и т.д.

Процесс настройки удаленного интерпретатора Pycharm для Django

Идем в file-> settings-> deployment

Вводим настройки подключения сервера, у кого какое (SFTP, FTP, и т.д.). В поле «root path» – нужно указать путь к папке с проектами. Во вкладке «Mapping» в поле «Deployment path on server» необходимо указать путь от «root path» к папке с проектом.

К примеру:
«root path» = /data/python
«Deployment path on server» = /project
Под deployment есть options, в них полезно выставить выгрузку файлов на сервер по горячим клавишам, например, ctrl+s и другие настройки.

Подготовка закончена, переходим соответственно к самой настройки удаленного интерпретатора.

Настройка интерпретатора не сильно отличается от настройки deployment (кнопкой «Fill from deployment server settings» можно заполнить часть настроек). Нажимаем «Configure Interpreters», выбираем remote, или если уже какой-то был создан, то с помощью плюсика. Далее необходимо указать путь к интерпретатору python на сервере. После нажимаем «ok» и немного подождать пока Pycharm скачает (создаст) образ skeleton python в месте с приложениями которые были установлены через pip или подобное ему, что очень удобно, в последствии можно спокойно переходить к этим файлам из кода!

Следующим шагом будет настройка запуска Django сервера используя средства Pycharm для разработки.

В инструментах с права выбираем «Edit configuration»

В появившемся окне вводим «host» 0.0.0.0 для того что бы с любого ip принимал вызовы и «port» который у Вас является свободным на сервере. Выбираете удаленный интерпретатор в поле «Python interpreter», который настроили раннее. В поле «Environment variables» необходимо указать переменную «DJANGO_SETTINGS_MODULE» и ее значение, состоящее из названия главного приложения Django и файла с настройками в нем.

На этом настройка удаленного интерпретатора завершена, для его запуска можно воспользоваться кнопкой на панели инструментов с права.

После с низу появится окно логов сервера со всевозможными инструментами.

Стоит отметить что помимо удаленной отладки в Pycharm встроили очень полезные инструменты(menu-> tools): SSH-клиент, Django-console, Python-console, Debug, и прочие.

На скриншоте ниже Django console и SSH-клиент в режиме сплит.

Заключение
Способ разработки (отладки), который был представлен выше, по сути является попыткой выхода на новый уровень. Развертывание разработки на локали – это как запатентованный проверенный способ, ну а описанный выше является новым подходом, и никто не гарантирует его поддержку, хотя JetBrains стараются, но как известно первые всегда набивают шишки. Удачи.

P. S.
Так же при настройке удаленного интерпретатора можно использовать virtualenv, где при разработке или доработке проекта можно проводить абсолютно независимые тесты и не влиять на сервер, но это отдельная тема.

Источник

Step 4. Create and Run your first Django project

Before you start

Make sure that the following prerequisites are met:

You are working with PyCharm version 2016.1 or later. If you still do not have PyCharm, download it from this page. To install PyCharm, follow the instructions, depending on your platform.

You have at least one Python interpreter properly installed on your computer. You can download an interpreter from this page.

You have Django package installed. To learn how to install packages using the PyCharm UI, read the section Install, uninstall, and upgrade packages. You can also install Django as described in the page How to install Django.

This tutorial has been created with the following assumptions:

Django 1.x (higher than Django 1.10).

The example used in this tutorial is similar to the one used in Django documentation. Sample project can be downloaded from here.

Creating a new project

Actually, all new projects are created same way: by clicking the New Project button in the Quick Start area of the Welcome screen:

If you have an already opened project, create a new one by choosing File | New Project. from the main menu.

Then, select the desired project type (here it is Django). Specify the project name and location.

Python best practice is to create a virtualenv for each project. In most cases, PyCharm create a new virtual environment automatically and you don’t need to configure anything. Still, you can preview and modify the venv options. Expand the Python Interpreter: New Virtualenv Environment node and select a tool used to create a new virtual environment. Let’s choose Virtualenv tool, and specify the location of the environment and the base Python interpreter used for the new virtual environment.

Читайте также:  Как правильно настроить роутер huawei ax3

Next, expand the More Settings node and specify the Django-related settings. In the Application name field specify the application name (here it is polls ).

Click Create — the Django project is ready.

Exploring project structure

As mentioned above, basically, the stub project is ready. It contains framework-specific files and directories. Same happens when you create a project of any supported type, be it Pyramid, or Google App Engine.

Let’s see how the structure of the new project is visible in the Project tool window.

Project view of the Project tool window

This view is displayed by default. It shows the Django-specific project structure: polls and mysite directories; also, you see the manage.py and settings.py files.

Note that you cannot see the .idea directory in this view:

Project Files view of the Project tool window

If for some reasons you would like to see contents of the .idea directory, choose the view Project Files : as you see, this view shows same directories and files, plus .idea directory, since is located under the project root:

Let’s return to the Project view.

What do we see in the Project view?

mysite directory is a container for your project. In the Project view it is denoted with bold font.

manage.py : This is a command-line utility that lets you interact with your Django project. Refer to the Django documentation for details.

The nested directory mysite is the actual Python package for your project.

mysite/__init__.py : This empty file tells Python that this directory should be considered a Python package.

mysite/wsgi.py : This file defines an entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

The nested directory polls contains all the files required for developing a Django application (at this moment, these files are empty):

Again, polls/_init_.py tells Python that this directory should be considered a Python package.

polls/models.py : In this file, we’ll create models for our application.

polls/views.py : In this file, we’ll create views.

templates directory is by now empty. It should contain the template files.

The nested directory migrations contains by now only the package file _init_.py , but will be used in the future to propagate the changes you make to your models (adding a field, deleting a model, and so on) into your database schema. Read the migrations description here.

Note that you can create as many Django applications as needed. To add an application to a project, run the startapp task of the manage.py utility ( Tools | Run manage.py task , then type startapp in the console).

Configuring the database

Now, when the project stub is ready, let’s do some fine tuning. Open for editing settings.py . To do it, select the file in the Project tool window, and press F4 . The file opens in its own tab in the editor.

Specify which database you are going to use in your application. For this purpose, find the DATABASES variable: click Ctrl+F , and in the search field start typing the string you are looking for. Then, in the ‘ENGINE’ line, add the name of your database management system after dot (you can use any one specified after comment, but for the beginning we’ll start with sqlite3 .)

In the ‘NAME’ line, enter the name of the desired database, even though it doesn’t yet exist.

Launching Django server

Since we’ve prudently chosen sqlite3 , we don’t need to define the other values (user credentials, port, and host). Let’s now check whether our settings are correct. This can be done most easily: just launch the runserver task of the manage.py utility: press Ctrl+Alt+R , and enter task name in the manage.py console:

Follow the suggested link and see the following page:

Creating models

Next, open for editing the file models.py , and note that import statement is already there. Then type the following code:

Creating database

We have to create tables for the new model. For this purpose, we’ll use the magic Ctrl+Alt+R shortcut to invoke the manage.py console. First command to perform is makemigrations polls :

Thus, you’ve told Django that two new models have been created, namely, Choice and Question , and created a migration:

Next, after the prompt, type the following command:

sqlmigrate polls 0001

Finally, run migrate command to actually create these tables in your database:

Performing administrative functions

First thing, create a superuser. To do that, type the createsuperuser command in the manage.py console, specify your email address, and password:

Since we’ve decided to enable site administration, PyCharm has already uncommented the corresponding lines in the file urls.py .

Open the admin.py file in the polls directory for editing, and see the following code that already exists:

However, we need to enable editing functionality for the admin site.

Preparing run/debug configuration

We are now ready to go to the admin page. Sure, it is quite possible to run the Django server, then go to your browser, and type the entire URL in the address bar, but with PyCharm there is an easier way: use the pre-configured Django server run configuration with some slight modifications.

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.

To open this run/debug configuration for editing, on the main toolbar, click the run/debug configurations selector, and then select Edit Configurations (or select Run | Edit Configurations from the main menu):

Читайте также:  Как настроить аирподсы с андроида

In the Run/Debug Configuration dialog, give this run/debug configuration a name (here it is mysite ), enable running the application in the default browser (select the checkbox Run browser ) and specify the page of the site to be opened by default (here this page is http://127.0.0.1:8000/admin/ ):

Launching the admin site

Now, to launch the application, press Shift+F10 , or click on the main toolbar to open the standard Django site login page:

After you log in, the administration page is displayed. It has a section Authentication and Authorization (Groups and Users) , but Polls is not available. Why so?

We must tell admin that Question objects have an admin interface; to do that, let’s open the file polls/admin.py for editing (select it in Project view and press F4 ), and type the following code:

Again pay attention to the code completion:

Refresh the page and see that Polls section with Questions appeared:

Click Add to create some questions.

Editing admin.py

However, each question has a number of choices, but choices are still not available. Again, open for editing the file polls/admin.py and change it as follows:

Now look at the Change question page:

Writing views

Open the file polls/views.py for editing and type the following Python code:

Next, add a new file to the polls directory with the name urls.py and type the following code in it:

Next, open for editing the file mysite/urls.py (which PyCharm has already created for you) and add a URL for the index page. You should end up with the following code:

Now, open the page 127.0.0.1:8000/polls/ and enjoy:

Next, let’s add more views. Again, add the following code to the file polls/views.py :

Wire these new views into the polls.urls module by adding the following url() calls :

If you now open the corresponding pages in your browser, you will see, for example:

Creating Django templates

As you see, the design of these pages is hardcoded in views. So, to make it more readable, you have to edit the corresponding Python code. Let’s then separate the visual representation of the output from Python — to do that, let’s create templates.

Open for editing the file polls/views.py and replace its contents with the following code:

By the way, pay attention to the import assistant that helps you create import statements.

The first thing you notice is an unresolved reference to the page index.html :

PyCharm suggests a quick-fix: if you click the light bulb, or press Alt+Enter , the corresponding template file is created in the templates folder (note that PyCharm also creates the directory polls where this template should reside):

By now, the file index.html is empty. Add the following code to it:

No polls are available.

For Django 3 and later, you need to use <% load static %>instead <% load staticfiles %>.

Note code completion in the template files! For example, when you type the opening <% , PyCharm adds the matching closing one %>automatically, placing the caret at the location of the future input. In HTML tags, code completion is also available.

Pay attention to the icons and that appear in the gutter of the files views.py and index.html respectively:

These icons enable you to jump between a view method and its template straight away. Read more about this kind of navigation in the articles Navigate between templates and views and Part 6. Django-specific navigation.

Using a Style Sheet

As you can see in the view file index.html , there is a reference to a Style Sheet, and it’s unresolved:

Resolve this reference in the following way:

Create directory. To do that, in the Project view, select the Python package polls , and then press Alt+Insert .

On the popup menu that appears, choose Directory , and specify the name of the directory structure static/polls .

Next, create a Style Sheet in this directory. To do that, choose the innermost directory polls , press Alt+Insert , choose the option Stylesheet , and enter style in the dialog that opens.

Provide some contents to the created Style Sheet, depending on your preferences. For example, we’d like to see a bulleted list of questions colored green:

Here we are!

Now let’s check the list of available polls. Our admin site is already running, and the easiest way to visit the page that contains the list of polls (the index page), is to specify its URL: in the address bar of the browser, instead of /admin/ , type /polls/ :

Test it…

Now let’s see how PyCharm helps simplify testing your application.

There is already the file tests.py in the polls directory. By now, this file is empty. Naturally, it is advisable to place the new tests in this particular file. For example, we’d like to make sure our poll is not empty:

To run this test, right-click the background of the file tests.py in the editor, choose the option Run , or just press Ctrl+Shift+F10 . PyCharm suggests two options: to run UnitTest (which is defined as the default test runner), or a Django test.

The test results show in the Test Runner tab of the Run tool window:

Summary

This brief tutorial is over. You have successfully created and launched a simple Django application. Let’s repeat what has been done with the help of PyCharm:

A Django project and application have been created

Источник

Оцените статью