Как создать проект django в pycharm
Перейти к содержимому

Как создать проект django в pycharm

  • автор:


Create a Django project

Django project is intended for productive web development with Django. PyCharm takes care of creating specific directory structure and files required for a Django application, and providing the correct settings.

Create a new Django project

From the main menu, choose File | New Project , or click the New Project button in the Welcome screen. New Project dialog opens.

In the New Project dialog, do the following:

Specify project type Django .

Specify project location.

Next, choose whether you want to create a new environment or use an existing interpreter, by clicking the corresponding radio-button.

If this option has been selected, choose the tool to be used to create a virtual environment. To do that, click the list and choose Virtualenv , Pipenv , Poetry , or Conda .

Next, specify the Location and Base interpreter of the new virtual environment.

Select the Inherit global site-packages checkbox if you want all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

If PyCharm detects no Python on your machine, it provides the following options:

Specify a path to the Python executable (in case of non-standard installation)

Download and install the latest Python versions from python.org

Install Python using the Command-Line Developer Tools (macOS only).

Downloading Python when creating a new project

Downloading Python when creating a new project

If this option has been selected, choose the desired interpreter from the list, or (if the desired interpreter is not found), click Add Interpreter and choose the interpreter.

When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.

Click ( More Settings ), and specify the following:

From the Template language list, select the language to be used.

In the Templates folder field, specify the directory where the templates will be stored, and where they will be loaded from. You can specify the name of the directory that doesn’t yet exist; in this case, the directory will be created.

In the Application name field, type the name of the Django application to be created.

The name of a Django application should not be the same as the Django project name.

If you need admin interface to be created, select the Enable Django admin checkbox.

If Django is missing in the selected interpreter, PyCharm displays an information message that Django will be downloaded.

Step 4. Create and Run your first Django project

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

This tutorial has been created with the following assumptions:

The example used in this tutorial is similar to the one used in Django documentation.

Creating a new project

From the main menu, choose File | New Project , or click the New Project button in the Welcome screen. New Project dialog opens.

In the New Project dialog, do the following:

Specify project type Django .

If required, change the default project location.

Select New environment using Virtualenv

Click ( More Settings ), and specify polls in the Application name field.

Exploring project structure

The newly created project contains Django-specific files and directories.

The structure of the project is visible in the Project tool window:

MyDjangoProject directory is a container for your project. It is denoted with bold font.

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

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

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

MyDjangoProject/settings.py : This file contains configuration for your Django project.

MyDjangoProject/urls.py : This file contains the URL declarations for your Django project.

MyDjangoProject/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:

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 will contain Django templates.

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.

Launching Django server

The Django server run/debug configuration is created automatically. If required, you can edit it by selecting the Edit Configurations command in the run/debug configuration list on the main toolbar:

Edit configurations

For example, you can choose to open a browser window automatically when the configuration is launched:

Run/Debug configuration for a Django server

Run the MyDjangoProject configuration by clicking . If a browser window does not open automatically, click the link in the Run tool window.

Django server test page

The following page opens:

Writing views

Django views are functions that take web request and return web responses. By convention, views are defined in views.py files inside of project and application directories.

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

The above message will be shown on the index page of the polls application.

Now we need to instruct the application to render the index view.

In the polls directory, create the file urls.py and type the following code in it:

Next, open the file MyDjangoProject/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:

Don’t forget to import django.urls.include !

Open the page in your browser. You should see the following text:

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

The above views take one argument ( question_id ), and then use it in the responses.

Map these new views to URLs by adding patterns in the /polls/urls.py file. The full code should look as follows:

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

Application views in browser

Creating database

By default, PyCharm automatically creates an SQLite database for a Django project.

We need to create the tables in the database for all applications in the current Django project. To do that, press Ctrl+Alt+R and type migrate followed by Enter in the manage.py console, that opens.

You should see Process finished with exit code 0 in the console output.

Creating and activating models

Django models define the fields and behaviors of your data. They are represented by Python classes, which are subclasses of the django.db.models.Model class.

Let’s create two models for our polls app: Question and Choice . To do that, open the file polls/models.py , and add the following code after the import statement:

Each model here has class variables represented by instances of a Field class:

The Question model:

question_text . An instance of the CharField class, contains the text of the question.

pub_date . An instance of the DateTimeField class, contains the publication date of the question.

‘date published’ is an optional first positional argument representing the human-readable name of the field.

The Choice model:

question . Association with a Question .

choice_text . An instance of the CharField class, contains the text of the choice.

votes . An instance of the IntegerField class, contains the vote tally.

For more information about model fields, refer to the Django documentation.

To make Django aware of the new models, run the following command in the manage.py console:


The polls/migrations directory now contains the migration file 0001_initial.py :

New Django migration

Migrations are human-editable files, in which Django stores changes to data models. To apply changes and create tables in the database for the two new models, run the migrate command again:


Performing administrative functions

Admin sites are used to add, edit, and otherwise manage the content. Django allows creating an admin site for your project automatically.

Setting up an admin site

Firstly, we need to create a superuser. To do that, type the createsuperuser command in the manage.py console, specify your email address, and password:

Now go to /admin/ on your Django server, for example, You should see the following 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 the admin that Question objects have an admin interface.

Adding content

Open the file polls/admin.py , and type the following code:

Refresh the page in the browser. The Polls section with Questions should appear:

Click Add to create a question:

Adding question in Django admin site

When you a ready, click SAVE .

The newly created question appears in the list as Question object (1) . Such naming makes content management complicated, as you have to open each question to see its text.

Let’s fix it by adding a __str__() method for both Question and Choice . Open polls/models.py and add the following lines:

You should end up with the following:

List of questions on the admin site

The list of questions now consists of human-readable names:

By design, each question must have a number of choices. However, choices are still not available in the admin interface. Let’s fix that.

Providing features

Open the file polls/admin.py and edit it to get the folowing result:

Now you can add choices to a question:

Creating Django templates

Until now, the design of the polls application pages has been hardcoded in views. To make the application usable, you need to separate the visual representation of the output from the Python code. That can be done by using Django templates.

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

You can see unresolved references to the template files index.html , detail.html , and results.html :

Unresolved references to Django templates

PyCharm suggests a quick-fix: if you click the light bulb, or press Alt+Enter , you can choose to create the corresponding template file in the templates folder:

Quick-fix for Django a template

PyCharm also creates the directory polls where this template should reside. Confirm this operation:

Confirmation of directory creation

By now, the file index.html is empty. Fill it with the following code:

The code generates the list of available questions, or displays "No polls are available" if there are none.

Pay attention to the icons and python typethat 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.

Now let’s add the detail.html template file with the code that generates a page with a question text, radio buttons for choices, and a Vote button:

The results.html template will generate a page with voting results for all choices and a link for answering the same question again. Create the file and fill it with the following code:

Go to in your browser and click the question link. You should see the following:

Django application question page

Select an option and click Vote . You will see a stub page with the "You are voting on question 1" message. That happens because we only have a dummy implementation of the vote() function in /polls/views.py . Let’s create a real one.

Open /polls/views.py and replace the vote() function definition with the following one:

This key elements of the above code are:

request.POST[‘choice’] returns the ID of the selected choice.

The except block is used to redisplay the question with an error message if no choice is provided.

HttpResponseRedirect redirects the user to a URL returned by the reverse() function.

The reverse() function is used to avoid hardcoding the URL. It accepts the name of the view that we want to pass control to and returns the URL of the voting results for the question.

Don’t forget to update the import statements in /polls/views.py as follows:

Now, if you go to again and answer the question, you should see the following:

Results of voting

Here we are!

Now all features of our application work as designed. You can use the admin site to add as many questions as you like. While the Django server is running, you can access the list of questions at and vote as many times as you like:

List of available polls

As you may have noticed, our app has a usability problem. When you click Vote again , it redirects you to the same question. A link to the list of all questions would be much more helpful. How do you fix that?

Check yourself

Edit the last line to get the following:

Testing the application

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:

Running tests


This brief tutorial is over. You have successfully created and launched a simple Django application. Let’s repeat what you managed to do with the help of PyCharm:

How to Create a Django Project with Pycharm IDE. Complete with Pictures!

D jango is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

In this article I’ll show you how to create a Django project with Pycharm Application. I’ll be creating the simplest django project possible. I use Windows operation system to run the PyCharm.

Okay Guys, Let’s begin….

1. Create New Repository on GitHub

To create a new repository, click “New”. Then, follow the steps which are shown below.

After create a repository, copy url on “Clone or Download”

2. Open the Repository with Git Version

If you still open the pycharm project, change the version of the project to Git. Follow the steps below!

Paste the link in the column provided and click “Clone”

Open file “.gitigrone” then add a line “.idea”

3. Use Virtual Environment

Use environment by click “File > Setting > Project > Project Interpreter >add” for details, follow the steps bellow.

4. Install Django

Open Terminal then install Django by typing “pip install django”

Создание первого веб-приложения с помощью Django

На днях мой брат спросил меня, могу ли я создать для него веб-сайт, с помощью которого можно было бы собирать данные, вводимые пользователями, выполнять некоторые вычисления и привлекать потенциальных клиентов. Я не работал над созданием сайтов со времен Geocities и MySpace. Ну, может быть, не так давно, но я довольно сильно отстал от темы, поскольку веб-программирование — не моя повседневная работа. Моим последним побочным проектом был сайт ресторана, созданный много лет назад, который я сделал с помощью PHP, поэтому я провел небольшое интернет-исследование, чтобы узнать, что популярно именно сейчас.


Простая в использовании IDE (интегрированная среда разработки). На моей нынешней работе (системным инженером) мне пришлось разрабатывать сценарии для автоматизации создания документов. Одна из проблем конкретного набора инструментов, который мы используем, заключается в том, что в нем нет редактора исходного кода. Нет подсветки синтаксиса или завершения кода. Это очень неудобно. Я понятия не имею, работает ли то, что я пишу, пока не запущу это и не увижу ошибки / предупреждения.

Отладка выполняется с помощью операторов печати. Так работать нельзя.

Этот простой язык программирования может пригодиться мне в будущем. В наши дни освоить большинство языков программирования довольно просто. Я искал тот, который имел бы хорошую поддержку (документацию, сообщество пользователей, учебные пособия), требовал бы минимального кода для достижения необходимого результата и был легко читаем.

Бонусом, поскольку я не являюсь веб-разработчиком, работающим на полную ставку, является то, что я смог бы потенциально использовать его для других приложений.

Работает быстро, без кучи ерунды. Поскольку это побочный проект, который дополняет мою постоянную работу и обязанности в семье, я не хотел тратить многие часы на настройку. Я хотел быстро получить прототип, чтобы можно было приступить к реальной работе.


Веб-фреймворк Django, использующий Python. Оказывается, этот инструмент автоматизации тестирования, который мы планировали использовать на работе, использует Python, так что это сыграло большую роль в том, что я обратил на него внимание, как на язык программирования общего назначения.

У меня был некоторый опыт работы с Java, но Spring оказался слишком тяжелым для этого проекта. Решения на основе Javascript, такие как стек MEAN, выглядели мощно, но я стараюсь не иметь с ними дел, если только это не (внешний интерфейс).

PyCharm. Выбрав Python, выбрать IDE было довольно просто. У PyCharm много фанатов, и я обнаружил, что к нему легко привыкнуть по сравнению с плагином PyDev в Eclipse или редактором IDLE, который поставляется вместе с Python.

Давайте создадим веб-приложение!

Внимание : все это я проделал на своем MacBook. Шаги будут отличаться, если вы используете Windows. Мой стационарный компьютер сейчас пылится и используется только эпизодически (для игр).

Установите Python

Загрузите Python с официального сайта . После установки убедитесь в том, что все готово. Откройте окно терминала и введите в него приведенные ниже команды.

Создайте виртуальную среду

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

Сначала создайте папку для проекта.

Затем создайте и активируйте виртуальную среду. Вы узнаете, что это работает, когда увидите «(myvenv)» в командной строке терминала.

Установите Django

Введите приведенную ниже строку, и веб-фреймворк Django будет установлен. Серьезно, это так просто.


Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *