Куда устанавливается django в windows

This document will guide you through installing Python 3.13 and Django on
Windows. It also provides instructions for setting up a virtual environment,
which makes it easier to work on Python projects. This is meant as a beginner’s
guide for users working on Django projects and does not reflect how Django
should be installed when developing changes for Django itself.

The steps in this guide have been tested with Windows 10. In other
versions, the steps would be similar. You will need to be familiar with using
the Windows command prompt.

Install Python¶

Django is a Python web framework, thus requiring Python to be installed on your
machine. At the time of writing, Python 3.13 is the latest version.

To install Python on your machine go to https://www.python.org/downloads/. The
website should offer you a download button for the latest Python version.
Download the executable installer and run it. Check the boxes next to “Install
launcher for all users (recommended)” then click “Install Now”.

After installation, open the command prompt and check that the Python version
matches the version you installed by executing:

py is not recognized or found

Depending on how you’ve installed Python (such as via the Microsoft Store),
py may not be available in the command prompt.

You will then need to use python instead of py when entering
commands.

About pip

pip is a package manager for Python and is included by default with the
Python installer. It helps to install and uninstall Python packages
(such as Django!). For the rest of the installation, we’ll use pip to
install Python packages from the command line.

Setting up a virtual environment¶

It is best practice to provide a dedicated environment for each Django project
you create. There are many options to manage environments and packages within
the Python ecosystem, some of which are recommended in the Python
documentation.
Python itself comes with venv for managing
environments which we will use for this guide.

To create a virtual environment for your project, open a new command prompt,
navigate to the folder where you want to create your project and then enter the
following:

...\> py -m venv project-name

This will create a folder called ‘project-name’ if it does not already exist
and set up the virtual environment. To activate the environment, run:

...\> project-name\Scripts\activate.bat

The virtual environment will be activated and you’ll see “(project-name)” next
to the command prompt to designate that. Each time you start a new command
prompt, you’ll need to activate the environment again.

Install Django¶

Django can be installed easily using pip within your virtual environment.

In the command prompt, ensure your virtual environment is active, and execute
the following command:

...\> py -m pip install Django

This will download and install the latest Django release.

After the installation has completed, you can verify your Django installation
by executing django-admin --version in the command prompt.

See Get your database running for information on database installation
with Django.

Colored terminal output¶

A quality-of-life feature adds colored (rather than monochrome) output to the
terminal. In modern terminals this should work for both CMD and PowerShell. If
for some reason this needs to be disabled, set the environmental variable
DJANGO_COLORS to nocolor.

On older Windows versions, or legacy terminals, colorama 0.4.6+ must be
installed to enable syntax coloring:

...\> py -m pip install "colorama >= 0.4.6"

See Syntax coloring for more information on color settings.

Common pitfalls¶

  • If django-admin only displays the help text no matter what arguments
    it is given, there is probably a problem with the file association in
    Windows. Check if there is more than one environment variable set for
    running Python scripts in PATH. This usually occurs when there is more
    than one Python version installed.

  • If you are connecting to the internet behind a proxy, there might be problems
    in running the command py -m pip install Django. Set the environment
    variables for proxy configuration in the command prompt as follows:

    ...\> set http_proxy=http://username:password@proxyserver:proxyport
    ...\> set https_proxy=https://username:password@proxyserver:proxyport
    
  • In general, Django assumes that UTF-8 encoding is used for I/O. This may
    cause problems if your system is set to use a different encoding. Recent
    versions of Python allow setting the PYTHONUTF8 environment
    variable in order to force a UTF-8 encoding. Windows 10 also provides a
    system-wide setting by checking Use Unicode UTF-8 for worldwide language
    support
    in Language ‣ Administrative Language Settings
    ‣ Change system locale
    in system settings.

Последнее обновление: 05.12.2023

Перед началом работы с Django нам естественно надо установить интерпретатор Python. Подоробнее об этом можно почитать
здесь.

Существуют разные способы установки Django. Рассмотрим рекомендуемый способ.

Пакетный менеджер pip

Пакеты Django размещаются в центральном репозитории для большинства пакетов Python — Package Index (PyPI). И для установки из этого репозитория
нам потребуется пакетный менеджер pip. Менеджер pip позволяет загружать пакеты и управлять ими.
Обычно при установке python также устанавливается и менеджер pip. В этом случае мы можем проверить версию менеджера, выполнив в командной строке/терминале команду
pip -V (V — с заглавной буквы):

C:\Users\eugen>pip -V
pip 23.3.1 from C:\Users\eugen\AppData\Local\Programs\Python\Python312\Lib\site-packages\pip (python 3.12)

C:\Users\eugen>

Если pip не установлен, то мы увидим ошибку типа

"pip" не является внутренней или внешней командой, исполняемой программой или пакетным файлом

В этом случае нам надо установить pip. Для этого можно выполнить в командной строке/консоли следующую команду:

python -m ensurepip --upgrade

Если pip ранее уже был установлен, то можно его обновить с помощью команды

python -m pip install --upgrade pip

Установка виртуальной среды

Виртуальная среда или venv не является неотъемлимой частью разработки на Django. Однако ее рекомендуется использовать, так как она
позволяет создать множество виртуальных сред Python на одной операционной системе. Благодаря виртуальной среде приложение может запускаться независимо от
других приложений на Python.

В принципе можно запускать приложения на Django и без виртуальной среды. В этом случае все пакеты Django устанавливаются глобально.
Однако что если после создания первого приложения выйдет новая версия Django? Если мы захотим использовать для второго проекта новую версию Django,
то из-за глобальной установки пакетов придется обновлять первый проект, который использует старую версию. Это потребует некоторой дополнительной работы по обновлению, так как
не всегда соблюдается обратная совместимость между пакетами.
Если мы решим использовать для второго проекта старую версию, то мы лишиемся потенциальных преимуществ новой версии. И использование
виртуальной среды как раз позволяет разграничить пакеты для каждого проекта.

Для работы с виртуальной средой в python применяется встроенный модуль venv

Итак, создадим вируальную среду. Вначале определим каталог для проектов django. Например, пусть это будет каталог C:\django.
Прежде всего перейдем в терминале/командной строке в этот каталог с помощью команды cd.

cd C:\django

Затем для создания виртуальной среды выполним следующую команду:

python -m venv .venv

Модулю venv передается название среды, которая в данном случае будет называться «.venv». Для наименования виртуальных сред нет каких-то определенных условностей. Пример консольного вывода:

C:\Users\eugen>cd C:\djangoПереход к папке будущей виртуальной среды

C:\django>python -m venv .venvСоздание виртуальной среды

C:\django>

После этого в текущей папке (C:\django) будет создан подкаталог «.venv».

Активация виртуальной среды

Для использования виртуальную среду надо активировать. И каждый раз, когда мы будем работать с проектом Django, связанную с ним виртуальную среду
надо активировать. Например, активируем выше созданную среду, которая располагается в текущем каталоге в папке .venv. Процесс активации немного отличается в зависимости от операционной системы и от того, какие инструменты применяются. Так, в Windows можно использовать командную строку и PowerShell,
но между ними есть отличия.

Активация в Windows в коммандной строке

Если наша ОС — Windows, то в папке .venv/Scripts/ мы можем найти файл activate.bat), который активирует
виртуальную среду. Так, в Windows активация виртуальной среды в коммандной строке будет выглядеть таким образом:

.venv\Scripts\activate.bat

Активация в Windows в PowerShell

Также при работе на Windows в папке .venv/Scripts/ мы можем найти файлactivate.ps1, который также активирует виртуальную среду,
но применяется только в PowerShell. Но при работе с PowerShell следует учитывать, что по умолчанию в этой оболочке запрещено применять скрипты. Поэтому
перед активацией среды необходимо установить разрешения для текущего пользователя. Поэтому для активации виртуальной среды в PowerShell необходимо выполнить две следующих команды:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
.venv\Scripts\Activate.ps1

Активация в Linux и MacOS

Для Linux и MacOS активация будет производиться с помощью следующей команды:

source .venv/bin/activate

Далее я буду приводить примеры на основе командной строки Windows, однако все остальные примеры не будут зависеть от того, что используется — PowerShell или командная строка, Windows, Linux или MacOS.
В любом случае после успешной активации слева от текущего каталога мы увидим в скобках название виртуальной среды:

C:\Users\eugen>cd C:\django

C:\django>python -m venv .venv

C:\django>.venv\Scripts\activate.batАктивация виртуальной среды

(.venv) C:\django> Виртуальная среда активирована

Установка Django

После активации виртуальной среды для установки Django выполним в консоли следующую команду

python -m pip install Django

Она устанавливает последнюю версию Django.

(.venv) C:\django>python -m pip install Django
Collecting Django
  Using cached Django-4.1-py3-none-any.whl (8.1 MB)
Collecting sqlparse>=0.2.2
  Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting tzdata
  Using cached tzdata-2022.1-py2.py3-none-any.whl (339 kB)
Collecting asgiref<4,>=3.5.2
  Using cached asgiref-3.5.2-py3-none-any.whl (22 kB)
Installing collected packages: tzdata, sqlparse, asgiref, Django
Successfully installed Django-4.1 asgiref-3.5.2 sqlparse-0.4.2 tzdata-2022.1

(.venv) C:\django>

Если нам интересует конкретная версия Django, то мы можем указать ее при установке:

python -m pip install django~=4.0.0

Проверка установки

Чтобы убедиться, что все установлено правильно, мы можем перейти к интерпретатору python. Для этого введем в терминале команду

python

И затем выполним последовательно следующие две инструкции:

>>> import django
>>> print(django.get_version())

Консольный вывод в моем случае:

(.venv) C:\django>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec  6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
4.1
>>>

Деактивация виртуальной среды

После окончания работы с виртуальной средой мы можем ее деактивировать с помощью команды:

deactivate

Среда разработки Django состоит из Python, Django и СУБД. Поскольку Django имеет дело с веб-приложениями, стоит упомянуть,
что вам также потребуется настроенный веб-сервер.

Шаг 1 — Установка Python

Django написан на чистом Python, поэтому вам нужно установить его в вашей системе. Последняя версия Django требует Python 2.6.5 или выше.

Если вы используете Linux или Mac OS X, возможно у вас уже установлен Python. Вы можете проверить это, набрав команду
python в командной строке. Если вы увидите что-то подобное, то Python установлен.

$ python
Python 2.7.5 (default, Jun 17 2014, 18:11:42)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2

В противном случае вы можете скачать и установить последнюю версию Python по ссылке.

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

Вы можете скачать последнюю версию Django по ссылке.

Установка в UNIX/Linux и Mac OS X

У вас есть два способа установки Django, если вы используете систему Linux или Mac OS:

  • Вы можете использовать менеджер пакетов вашей ОС или воспользоваться easy_install или pip, если они установлены.
  • Установите его вручную, используя официальный архив, который вы скачали ранее.

Мы рассмотрим второй вариант, так как первый зависит от дистрибутива вашей ОС. Если вы решили следовать первому варианту,
будьте осторожны с версией Django, которую вы устанавливаете.

Допустим, вы получили свой архив по ссылке выше, он должен представлять собой что-то вроде Django-x.xx.tar.gz:

Распакуйте и установите его:

$ tar xzvf Django-x.xx.tar.gz
$ cd Django-x.xx
$ sudo python setup.py install

Вы можете проверить текущее состояние установки, выполнив команду ниже:

$ django-admin.py --version

Если вы увидите на экране текущую версию Django, то все установлено.

Примечание. В некоторых версиях Django будет просто django-admin, без “.py”.

Установка в Windows

Предполагается, что на вашем компьютере уже есть Python и архив с Django.

Первым делом проверьте PATH.

В некоторых версиях Windows (например, Windows 7) вам будет необходимо убедиться, что системная переменная PATH содержит
следующий путь: **C:\Python34;C:\Python34\Lib\site-packages\django\bin**, конечно, с вашей версией Python.

Затем распакуйте Django:

c:\>cd c:\Django-x.xx

А затем установите его, выполнив следующую команду, для которой вам понадобятся права администратора в командной оболочке Windows “cmd”:

c:\Django-x.xx>python setup.py install

Чтобы проверить установку, откройте командную строку и введите следующую команду:

c:\>python -c "import django; print(django.get_version())"

Если вы увидите на экране текущую версию Django, то все установлено.

ИЛИ ЖЕ

Запустите командную оболочку “cmd” и введите python:

c:\> python
>>> import django
>>> django.VERSION

Шаг 3 — Настройка базы данных

Django поддерживает несколько основных СУБД, вы можете настроить любую из них в зависимости от вашего предпочтения.

  1. MySQL
  2. PostgreSQL
  3. SQLite 3
  4. Oracle
  5. MongoDb
  6. GoogleAppEngine DataStore

Вы можете обратиться к соответствующей документации по установке и настройке базы данных на ваш выбор.

Примечание. Номера 5 и 6 — базы данных NoSQL.

Шаг 4 — Веб-сервер

Django поставляется с легким веб-сервером для разработки и тестирования приложений. Этот сервер предварительно настроен
для работы с Django, и, что более важно, он перезапускается всякий раз, когда вы изменяете код.

Тем не менее Django поддерживает Apache и другие популярные веб-серверы, такие, как Lighttpd. Мы обсудим оба варианта
в следующих главах, работая с разными примерами.

Источник: Django — Environment

Социальные сети проекта:

  • Telegram
  • VK
  • Twitter

Подпишись, чтобы ничего не пропустить!

Introduction

The Python ecosystem has a lot of web frameworks. One that has consistently been popular is the Django framework. It’s popular for being robust, secure, and allows developers to develop projects fast and meet their deadlines. It is free and open-source, and it works on both Windows and *nix systems.

In this tutorial, you will learn how to install Django on Windows using pip. After that, you will verify the installation, create a project, and start a Django development server.

Prerequisites

Before you install Django, you must make sure that Python is installed on your system. You can check out this guide — how to install python on windows to learn how to do it.

The commands that you will run in this tutorial were tested on the PowerShell shell, but most commands should work on Windows Command Prompt(CMD) with a few exceptions. For a smooth experience, I would suggest you use PowerShell for this tutorial.

Step 1 — Opening PowerShell

First, you need to open PowerShell on your computer. You can do that by searching for PowerShell in the Windows search box or you can open the Run dialog box by holding the Windows logo key and R(WIN+R). Once the dialog is open, type powershell, and then click OK.

You should now have the PowerShell window opened.

Picture of the author

Now that you have opened PowerShell on your computer, you’ll verify the installation of Python in the next section.

Step 2 — Verifying Python Installation

Before you install Django, first, you need to make sure that you installed Python on your system.

To do that, type the following command in PowerShell prompt to verify the installation:

  1. python -V

-V option logs the Python version installed on your system.

After running the command, you should see output like this:

PS C:\Users\Username> python -V
Python 3.9.7

At the time of writing, it is Python 3.9.7. You might have a different version from mine, and that’s fine. As long as you see the Python version logged, Python is installed on your system.

Now that you’ve confirmed Python is installed on your system, you will upgrade pip.

Step 3 — Upgrading Pip

Python comes with pip by default. But most of the time, it comes with an old version. it’s always a good practice to upgrade pip to the latest version.

Enter the following command to upgrade pip on your system:

  1. python -m pip install --upgrade pip

You’ll get output identical to the following screenshot showing you that the upgrade was a success:

Picture of the author

Now you’ve upgraded pip, you’ll create the project directory where you’ll install Django.

Step 4 — Creating a Project Directory

In this section, you will create a directory that will contain your Django application. We will name it django_project since this tutorial is a demo. But in a real project, you can give the directory a suitable name, such as forum, blog, etc.

Change into your Desktop directory with the cd command:

  1. cd Desktop

Create the directory using the mkdir command:

  1. mkdir django_project

Move into the django_project directory using the cd command:

  1. cd django_project

Your prompt should now show you that you’re in the django_project directory as shown in the following output:

  1. PS C:\Users\Stanley\Desktop\django_project>

Now that you’ve created the working directory for your project, you’ll create a virtual environment where you’ll install Django.

Step 5 — Creating the Virtual Environment

In this step, you’ll create a virtual environment for your project. A virtual environment is an isolated environment in Python where you can install the project dependencies without affecting other Python projects. This lets you create different projects that use different versions of Django.

If you don’t use a virtual environment, your projects in your system will use the same Django version installed globally. This might look like a good thing until the latest version of Django comes out with breaking changes causing your projects to fail altogether.

You can learn more about the virtual environment by following Python Virtual Environments: A Primer.

To create a virtual environment, type the following command and wait for a few seconds:

  1. python -m venv venv

The command will create a directory called venv inside your project directory.

Next, confirm the venv directory has been created by listing the directory contents using the ls command:

  1. ls

You should see the directory venv in the output as shown in the following screenshot:

Picture of the author

Now you’ve created the virtual environment directory, you’ll activate the environment.

Step 6 — Activating the Virtual Environment

In this section, you’ll activate the virtual environment in your directory.

Run the following command to activate the virtual environment:

  1. venv\Scripts\activate

After you run the command, you will see

a (venv) at the beginning of the prompt. This shows that the virtual environment is activated:

(venv) PS C:\Users\Stanley\Desktop\django_project>

If you run into the error shown in the following screenshot on PowerShell when activating the virtual environment, for the sake of brevity, I described the reason and the solution in another post. Follow Solution to «Running Scripts Is Disabled On This System» Error on PowerShell and don’t close your PowerShell:

Picture of the author

Now that you’ve activated the virtual environment for your project, the moment you’ve been waiting for is here. It’s time to install Django!

Step 7 — Installing Django

In this section, you will install Django on your system using pip.

Run the following command to install Django using pip install:

  1. pip install django

The command will install the latest version of Django. You should see Django being downloaded as shown in the following screenshot:

Picture of the author

If you want to install a different Django version, you can specify the version as follows:

  1. pip install django==3.1

Once the installation finishes, you need to verify that Django has been installed. To do that, type the following command:

  1. django-admin --version

You will get output showing you the Django version installed on your system:

(venv) PS C:\users\stanley\Desktop\django_project> django-admin --version
3.2.7

At the time of writing, the latest Django version is 3.2.7, and that’s why my output shows that.

You’ve now installed Django on your system, great job! You’ll begin to create a Django project.

Step 8 — Creating the Django Project

Now it’s time to create a project. A project has a different meaning from what you may be used to. The Django documentation defines it as:

A Python package – i.e. a directory of code – that contains all the settings for an instance of Django. This would include database configuration, Django-specific options and application-specific settings.

You create a project by using the command-line utility django-admin that comes with Django. The command generates files where you can configure the settings for your database, add third-party packages for your project to mention a few.

Create the project using the django-admin startproject command:

  1. django-admin startproject test_project

Change into the test_project directory:

  1. cd test_project

Type the following command to see the contents in the project directory:

  1. ls test_project

You will get output similar to this:

Output

(venv) PS C:\users\stanley\Desktop\django_project\test_project> ls Directory: C:\users\stanley\Desktop\django_project\test_project Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 9/4/2021 1:25 AM test_project -a---- 9/4/2021 1:25 AM 690 manage.py

The directory test_project contains Django configuration files. The manage.py file comes in handy when starting a development server, and that’s what you will do in the next step.

Step 9 — Running the Development Server

Now that the project has been created, we will start the Django development server.

Start the development server using the manage.py runserver command:

  1. python manage.py runserver

Picture of the author

Next, visit http://127.0.0.1:8000/ in your web browser. You should see a page similar to the following screenshot:

Picture of the author

Tip You can stop the server by holding CTRL+C. To deactivate the virtual environment, you can type deactivate on the prompt.

Now, you are ready to start developing your project.

Conclusion

You have come to the end of this tutorial, you learned how to install Django on Windows, verifying the installation and you also learned how to create a Django project, and start a development server. You can visit Django’s official tutorial to learn how to build an application, see Writing your first Django app, part 1.

Thank you for reading and don’t forget to follow me on Twitter for more tips.

Примечание: если ты используешь Chromebook, пропусти эту главу, но выполни инструкции по настройке для Chromebook

Примечание: если ты уже выполнила установку — можешь пропустить эту часть и сразу перейти к следующей главе!

Отдельные части этой главы основаны на учебных пособиях Geek Girls Carrots (https://github.com/ggcarrots/django-carrots).

Отдельные части этой главы основаны на учебном пособии django-marcador, лицензированном под Creative Commons Attribution-ShareAlike 4.0 International License. Руководство django-marcador защищено авторским правом Markus Zapke-Gründemann et al.

Виртуальное окружение

Перед установкой Django мы попросим тебя установить крайне полезный инструмент, который поможет тебе содержать среду разработки в чистоте. Можно пропустить этот шаг, но мы очень советуем этого не делать. Использование лучших рекомендаций с самого начала убережёт от многих проблем в будущем!

Итак, давай создадим виртуальное окружение (оно также называется virtualenv). Virtualenv будет изолировать настройки Python/Django для каждого отдельного проекта. Это значит, что изменения одного сайта не затронут другие сайты, которые ты разрабатываешь. Удобно, правда?

Всё, что тебе нужно сделать — найти директорию, в которой мы создадим virtualenv; домашний каталог вполне подойдёт. Для Windows адрес будет выглядеть так: C:\Users\Name (где Name — твоё имя пользователя).

Примечание: Если ты работаешь в Windows, удостоверься, что в названии директории нет специальных символов или символов с диакритическими знаками; если в твоём имени пользователя есть такие символы, выбери другую директорию, например, C:\djangogirls.

Мы будем использовать отдельную директорию djangogirls в домашнем каталоге:

command-line

$ mkdir djangogirls
$ cd djangogirls

Мы создадим виртуальное окружение под именем myvenv. В общем случае команда будет выглядеть так:

command-line

$ python3 -m venv myvenv

Виртуальное окружение: Windows

Чтобы создать новое virtualenv, тебе нужно открыть командную строку и набрать python -m venv myvenv. Это будет выглядеть так:

command-line

C:\Users\Name\djangogirls> python -m venv myvenv

Здесь myvenv — имя твоего virtualenv. Ты можешь выбрать другое имя, но используй только строчные буквы, без пробелов и специальных символов. Имя виртуального окружения выбирай покороче — тебе придётся часто его набирать!

Виртуальное окружение: Linux и macOS

В Linux и macOS достаточно набрать python3 -m venv myvenv, чтобы создать virtualenv:

command-line

$ python3 -m venv myvenv

myvenv — имя виртуального окружения virtualenv. Можешь выбрать другое имя, но используй только строчные буквы и никаких пробелов. Имя виртуального окружения лучше выбирать покороче — набирать его предстоит не раз!

Примечание: В некоторых версиях Debian/Ubuntu может произойти следующая ошибка:

command-line

The virtual environment was not created successfully because ensurepip is not available.  On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
   apt install python3-venv
You may need to use sudo with that command.  After installing the python3-venv package, recreate your virtual environment.

В таком случае следуй приведённым инструкциям и установи пакет python3-venv:

command-line

$ sudo apt install python3-venv

Примечание: В некоторых версиях Debian/Ubuntu при таком способе создания виртуального окружения ты можешь получить такую ошибку:

command-line

Error: Command '['/home/eddie/Slask/tmp/venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1

Чтобы обойти её, используй команду virtualenv.

command-line

$ sudo apt install python-virtualenv
$ virtualenv --python=python3.12 myvenv

Примечание: Если ты получаешь следующую ошибку

command-line

E: Unable to locate package python3-venv

то запусти команду:

command-line

sudo apt install python3.12-venv

Работаем с virtualenv

Указанная выше команда создаст директорию myvenv (или другую, в зависимости от выбранного тобой имени), которая будет содержать виртуальное окружение (по сути — набор файлов и папок).

Работаем с virtualenv: Windows

Запусти виртуальное окружение, выполнив:

command-line

C:\Users\Name\djangogirls> myvenv\Scripts\activate

ПРИМЕЧАНИЕ: в Windows 10 при работе в Windows PowerShell ты можешь получить ошибку вида execution of scripts is disabled on this system. В этом случае открой ещё одно окно Windows PowerShell, выбрав опцию «Запустить от имени Администратора». Затем перед использованием виртуального окружения попробуй запустить следующую команду:

command-line

C:\WINDOWS\system32> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
    Execution Policy Change
    The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A

Работаем с virtualenv: Linux и macOS

Запусти виртуальное окружение, выполнив:

command-line

$ source myvenv/bin/activate

Не забудь поменять myvenv на выбранное тобой имя для virtualenv!

ПРИМЕЧАНИЕ: иногда команда source может быть недоступна. В таком случае используй следующий метод:

command-line

$ . myvenv/bin/activate

Ты поймёшь, что virtualenv запущено, когда увидишь префикс (myvenv) в начале приглашения командной строки.

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

Отлично, теперь мы будем хранить все важные зависимости в одном месте. Наконец можно установить Django!

Установка Django

После запуска virtualenv ты можешь установить Django.

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

command-line

(myvenv) ~$ python3 -m pip install --upgrade pip

Установка библиотек через указание требований

Файл с требованиями (requirements) хранит список зависимостей, которые нужно установить с помощью
pip install:

Для начала создай файл requirements.txt внутри директории djangogirls/, используя текстовый редактор, который ты установила ранее. Просто создай в редакторе новый файл, а затем сохрани его под именем requirements.txt в директории djangogirls/. После этого твоя директория будет выглядеть так:

djangogirls
└───requirements.txt

В файл djangogirls/requirements.txt нужно добавить такой текст:

djangogirls/requirements.txt

Django~=5.1.2

Теперь выполни команду pip install -r requirements.txt, чтобы установить Django.

command-line

(myvenv) ~$ pip install -r requirements.txt
Collecting Django~=5.1.2 (from -r requirements.txt (line 1))
  Downloading Django-5.1.2-py3-none-any.whl (7.1MB)
Installing collected packages: Django
Successfully installed Django-5.1.2

Установка Django: Windows

Если при запуске pip в Windows ты получаешь сообщение об ошибке, проверь, что путь к директории с проектом не содержит пробелов или специальных символов (C:\Users\User Name\djangogirls). Если проблема в этом, то, пожалуйста, перенеси свой проект в другое место, адрес которого не будет содержать пробелов и специальных символов (предлагаем C:\djangogirls). Создай новое виртуальное окружение в новой директории, после этого удали старое и попробуй запустить команды выше заново (перемещение виртуального окружения не сработает, поскольку в нём используются абсолютные пути).

Установка Django: Windows 8 и Windows 10

При попытке установки Django твоя командная строка может зависнуть. Если это произошло, вместо приведённой выше команды используй:

command-line

C:\Users\Name\djangogirls> python -m pip install -r requirements.txt

Установка Django: Linux

При возникновении ошибки при вызове pip под Ubuntu 12.04, пожалуйста, запусти `python -m pip install -U —force-reinstall pip`, чтобы исправить установку pip в virtualenv.

Вот и всё! Теперь ты (наконец-то) готова создать своё Django-приложение!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как узнать версию материнской платы windows 7
  • Программы для очистки диска с windows 10 от ненужных файлов программы
  • How to turn off windows defender smartscreen
  • Как открыть c windows memory dmp
  • Kb2603229 windows 7 x64