Создание django проекта visual studio code
Visual Studio the text editor is known as Visual Studio Code is Microsoft’s free text editor that runs on Windows, Linux, and macOS. It’s a recent entrant to the market; Microsoft released the product as a public preview at the end of 2015, posting the open source code to Github, before making it available as a general release in April 2016.
Despite its newbie status, Visual Studio Code has rapidly gained popularity among developers. Some may argue that it is not a real IDE, but merely an advanced text editor. But in my opinion, after installing a number of extensions, it becomes almost a full-fledged IDE with very rich functionality.
Additionally, despite being an Electron-based application, it is quite lightweight and responsive (in contrast to for example Atom, which is very slow and resource intensive).
This tutorial will go through Installation and setup of the VS code for Python and Django projects on your machine.
Installing Visual Studio Code
Visual Studio Code is a free text editor so to download it you just have to visit their official site and download the file depending on your operating system. So visit Vscode's-website and download the latest stable build for your OS and once the download is finished install the editor and launch the app.
The best thing about VScode is that it comes with a built-in terminal which comes handy for Django projects press Ctrl+Shift+` to invoke the terminal.
Note that in windows powershell may seem weird for new users it is recommended to use Python debug console or CMD.
Configuring Python
To enjoy Pythonic features such as Linting, Debugging (multi-threaded, remote), Intellisense, code formatting, refactoring, unit tests, snippets, and more you need to install Python extension for Vscode.
To install an extension press Ctrl+Shift+x or click the extension icon.
Now search for Python and install the one published by Microsoft.
Adding Extension For Django
Search for Djaneiro this extension provides a collection of snippets for Django templates, models, views, fields & forms ported from Djaneiro for SublimeText.
Selecting Python Environment
Press CTRL+SHIFT+P(CMD+SHIFT+P for MacOS) and type Python: Select Interpreter and select the environment for your project. You can see the active environment at the bottom left of the editor.
Installing Theme
The default Vscode theme is great in itself however there are plenty for fabulous free themes available for download.
My favorite one is Night Owl+ so let's install night owl+ theme from extensions.
To change the theme go to, file>Preference> color theme
And select the theme that you prefer.
Notice below the color theme there is an option for the file icon theme.
Download Material Icon Theme from extensions store and c lick on that and select the icon theme this will give different file icons for different files.
After that restart VS code to activate the extensions. Now open any of your Django project you should get this beautiful view.
Your font might look different I am using Fira code font here.
Configuring Additional Useful Settings
Go to file> preferece> settings then open settings.json from there.
In USER SETTINGS inside the curly braces < >add the following Settings.
To use the above features, the editor will prompt you to install pylint and autopep8, or you can install them directly in the virtual environment.
Some useful VScode extensions:
- Code Spell Checker
- Django
- Git History
Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.
In this tutorial, you use Python 3 to create the simplest Python "Hello World" application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).
This tutorial introduces you to VS Code as a Python environment, primarily how to edit, run, and debug code through the following tasks:
- Write, run, and debug a Python "Hello World" Application
- Learn how to install packages by creating Python virtual environments
- Write a simple Python script to plot figures within VS Code
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:
- VS Code
- VS Code Python extension
- Python 3
Install Visual Studio Code and the Python Extension
If you have not already done so, install VS Code.
Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it's published by Microsoft.
Install a Python interpreter
Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.
Windows
Note: If you don't have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of Python 3.7, Python 3.8, Python 3.9, and Python 3.10. Be aware that you might have compatibility issues with some packages using this method.
macOS
The system install of Python on macOS is not supported. Instead, an installation through Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.
Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.
Linux
The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.
Other options
Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.
Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you'll also want to install the Remote - WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.
Verify the Python installation
To verify that you've installed Python successfully on your machine, run one of the following commands (depending on your operating system):
Linux/macOS: open a Terminal Window and type the following command:
Windows: open a command prompt and run the following command:
If the installation was successful, the output window should show the version of Python that you installed.
Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).
Start VS Code in a project (workspace) folder
Using a command prompt or terminal, create an empty folder called "hello", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:
Note: If you're using an Anaconda distribution, be sure to use an Anaconda command prompt.
By starting VS Code in a folder, that folder becomes your "workspace". VS Code stores settings that are specific to that workspace in .vscode/settings.json , which are separate from user settings that are stored globally.
Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.
Select a Python interpreter
Python is an interpreted language, and in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.
From within VS Code, select a Python 3 interpreter by opening the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, see Configuring Python environments.
Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda) , for example Python 3.7.3 64-bit ('base':conda) .
Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.
Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.
Create a Python Hello World source code file
From the File Explorer toolbar, select the New File button on the hello folder:
Name the file hello.py , and it automatically opens in the editor:
By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.
Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.
Now that you have a code file in your Workspace, enter the following source code in hello.py :
When you start typing print , notice how IntelliSense presents auto-completion options.
IntelliSense and auto-completions work for standard Python modules as well as other packages you've installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg. :
Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file ( ⌘S (Windows, Linux Ctrl+S ) ).
For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.
Run Hello World
It's simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.
The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):
There are three other ways you can run Python code within VS Code:
Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):
Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.
From the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.
Configure and run the debugger
Let's now try debugging our simple Hello World program.
First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9 . Alternately, just click in the editor's left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.
Next, to initialize the debugger, press F5 . Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.
Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.
These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.
You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.
The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.
A debug toolbar appears along the top with the following commands from left to right: continue ( F5 ), step over ( F10 ), step into ( F11 ), step out ( ⇧F11 (Windows, Linux Shift+F11 ) ), restart ( ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 ) ), and stop ( ⇧F5 (Windows, Linux Shift+F5 ) ).
The Status Bar also changes color (orange in many themes) to indicate that you're in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.
To continue running the program, select the continue command on the debug toolbar ( F5 ). The debugger runs the program to the end.
Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg , hovering over the variable will display the string Hello world in a box above the variable.
You can also work with variables in the Debug Console (If you don't see it, select Debug Console in the lower right area of VS Code, or select it from the . menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:
Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. "Hello World" appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.
If you restart the debugger, the debugger again stops on the first breakpoint.
To stop running a program before it's complete, use the red square stop button on the debug toolbar ( ⇧F5 (Windows, Linux Shift+F5 ) ), or use the Run > Stop debugging menu command.
For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.
Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn't stop the program. For more information, see Logpoints in the main VS Code debugging article.
Install and use packages
Let's now run an example that's a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)
Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py , and paste in the following source code:
Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter .
Next, try running the file in the debugger using the "Python: Current file" configuration as described in the last section.
Unless you're using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, "ModuleNotFoundError: No module named 'matplotlib'". Such a message indicates that the required package isn't available in your system.
To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) ). This command opens a command prompt for your selected interpreter.
A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:
Note: For additional information about virtual environments, see Environments.
Create and activate the virtual environment
Note: When you create a new virtual environment, you should be prompted by VS Code to set it as the default for your workspace folder. If selected, the environment will automatically be activated when you open a new terminal.
For Windows
If the activate command generates the message "Activate.ps1 is not digitally signed. You cannot run this script on the current system.", then you need to temporarily change the PowerShell execution policy to allow scripts to run (see About Execution Policies in the PowerShell documentation):
For macOS/Linux
Select your new environment by using the Python: Select Interpreter command from the Command Palette.
Install the packages
Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:
Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.
For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.
Next steps
You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.
To learn to build web apps with the Django and Flask frameworks, see the following tutorials:
В проекте Visual Studio теперь имеются только компоненты на уровне сайта проекта Django, с помощью которых можно выполнить одно или несколько приложений Django. Следующий шаг — создание первого одностраничного приложения.
На этом шаге вы научитесь делать следующее:
- Создание одностраничного приложения Django (шаг 2–1).
- Запуск приложения из проекта Django (шаг 2–2).
- Преобразование представления с помощью HTML (шаг 2–3).
- Преобразование представления с помощью шаблона страницы Django (шаг 2–4).
Шаг 2-1. Создание приложения со стандартной структурой
Приложение Django обычно начинается со стандартного набора файлов. Visual Studio предоставляет шаблоны для инициализации приложения Django в проекте Django, а также встроенную команду меню, которая выполняет ту же функцию:
- Шаблоны. В обозревателе решений щелкните проект правой кнопкой мыши и выберите Добавить >Новый элемент. В диалоговом окне Добавить новый элемент выберите шаблон Приложение Django 1.9, укажите имя приложения в поле Имя и нажмите кнопку Добавить.
Встроенная команда. В обозревателе решений щелкните проект правой кнопкой мыши и выберите Добавить > Приложение Django. Команда запросит имя. Укажите имя приложения в поле Имя нового приложения и нажмите кнопку ОК.
Создайте приложение с именем HelloDjangoApp, используя любой из методов. Теперь в проекте создается папка HelloDjangoApp. Эта папка содержит следующие элементы:
При использовании имени HelloDjangoApp содержимое файла apps.py выглядит следующим образом:
Вопрос. Отличается ли создание приложения Django в Visual Studio от создания приложения в командной строке?
Ответ. Если выполнить команду Добавить > Приложение Django или Добавить > Новый элемент в шаблоне приложения Django, будут созданы те же файлы, что и при использовании команды Django manage.py startapp . Преимуществом создания приложения в Visual Studio является то, что папка приложения и все ее файлы автоматически интегрируются в проект. С помощью той же команды Visual Studio можно создать любое количество приложений в проекте.
Шаг 2-2. Запуск приложения из проекта Django
Теперь, если вы снова запустите проект в Visual Studio (используя кнопку панели инструментов или выполнив команды Отладка > Начать отладку), отобразится страница по умолчанию. Содержимое приложения не отобразится, так как для этого необходимо определить страницу приложения и добавить приложение в проект Django.
В папке HelloDjangoApp измените файл views.py, чтобы определить представление с именем index:
В папке BasicProject (созданной в шаге 1) измените файл urls.py, чтобы он соответствовал следующему коду (при необходимости можно оставить полезные комментарии):
Каждый шаблон URL-адреса описывает представления, в которые Django направляет определенные URL-адреса, связанные с сайтом (это фрагмент после https://www.domain.com/ ). Первая запись в urlPatterns , которая начинается с регулярного выражения ^$ , — это маршрутизация для корня сайта, "/". Вторая запись ^home$ конкретно направляет /home. В одном представлении может быть несколько маршрутов.
Фиксация в системе управления версиями
После внесения изменений в код и их успешного тестирования можно просмотреть и зафиксировать изменения в системе управления версиями. В дальнейших шагах, когда вы получите напоминание о повторной фиксации изменений в системе управления версиями, вам будет необходимо вернуться к этому разделу.
Вопрос. Что означает префикс r перед строками маршрутизации?
Ответ. Префикс r в строке Python означает raw (без обработки). Это предписывает Python не использовать escape-символы в строке. В регулярных выражениях используется множество специальных символов. Использование префикса "r" значительно упрощает чтение строк по сравнению с escape-символами "\".
Вопрос. Что означают символы ^ и $ в записях маршрутизации URL-адреса?
Если вы не используете в конце регулярного выражения символ $, как в случае с ^home , то шаблон URL-адреса соответствует любому URL-адресу, который начинается с home, например home, homework, homestead и home192837.
Шаг 2-3. Преобразование представления с помощью HTML
Чтобы быстро остановить и перезапустить проект, выполните команду меню Отладка > Перезапустить (CTRL+SHIFT+F5) или нажмите кнопку Перезапуск на панели инструментов отладки:
Шаг 2-4. Преобразование представления с помощью шаблона страницы
Создание HTML в коде хорошо подходит для небольших страниц. Однако по мере усложнения страниц необходимо хранить статические HTML-части страницы (вместе со ссылками на файлы CSS и JavaScript) в виде "шаблонов страниц". Таким образом, вы можете вставлять динамически создаваемое кодом содержимое в шаблоны страниц. В предыдущем разделе только дата и время вызова now.strftime являлись динамическими. Это значит, что остальное содержимое можно поместить в шаблон страницы.
Шаблон страницы Django — это блок HTML-кода, содержащий несколько токенов замены, которые называются переменными. Они разделены > , например > . Затем модуль шаблонов Django заменяет переменные динамическим содержимым, предоставленным в коде.
В следующих шагах показано использование шаблонов страницы.
В папке BasicProject, содержащей проект Django, откройте файл settings.py. Добавьте в список INSTALLED_APPS имя приложения HelloDjangoApp. Добавление приложения в список указывает проекту Django, что существует папка с именем HelloDjangoApp, содержащая приложение:
В файле settings.py убедитесь, что объект TEMPLATES содержит следующую строку (включена по умолчанию). Следующий код указывает Django искать шаблоны в папке templates установленного приложения:
В папке HelloDjangoApp откройте файл шаблона страницы templates/HelloDjangoApp/index.html (или templates/index.html в Visual Studio 2017 15.7 и более ранних версий), чтобы увидеть, что в нем находится только одна переменная > :
В папке HelloDjangoApp откройте файл views.py и замените функцию index приведенным ниже кодом, в котором используется вспомогательная функция django.shortcuts.render . Вспомогательная функция render предоставляет упрощенный интерфейс для работы с шаблонами страницы. Сохраните все существующие операторы from .
Первый аргумент в render — это объект запроса, за которым следует относительный путь к файлу шаблона в папке templates приложения. Файл шаблона называется в соответствии с поддерживаемым представлением, если это уместно. Третий аргумент в render представляет собой словарь переменных, к которым относится шаблон. Вы можете добавить объект в словарь. В этом случае переменная в шаблоне может ссылаться на > .
Обратите внимание, что HTML-код, используемый в свойстве content , отображается только в качестве обычного текста, так как функция render автоматически экранирует этот HTML-код. Автоматическое экранирование предотвращает случайные уязвимости к атакам путем внедрения кода. Разработчики часто собирают входные данные с одной страницы и используют их в качестве значения на другой странице с помощью заполнителя шаблона. Экранирование служит напоминанием о том, что HTML-код рекомендуется хранить в шаблоне страницы, а не в коде. Кроме того, при необходимости можно легко создать дополнительные переменные. Например, измените файл index.html в папке шаблонов, чтобы он соответствовал следующей разметке. Следующая разметка добавляет заголовок страницы и сохраняет все форматирование в шаблоне страницы:
Затем запишите функцию представления index указанным ниже образом, чтобы предоставить значения для всех переменных в шаблоне страницы:
Остановите сервер и перезапустите проект. Убедитесь, что страница отображается корректно:
В Visual Studio 2017 версии 15.7 и более ранних версий: в качестве последнего шага переместите шаблоны во вложенную папку с именем, совпадающим с именем вашего приложения. При использовании вложенной папки создается пространство имен, что позволяет избежать потенциальных конфликтов с другими приложениями, которые можно добавить в проект. (Шаблоны в VS 2017 версии 15.8 и более поздних версий реализуют такое поведение автоматически.) Для этого создайте в папке templates вложенную папку с именем HelloDjangoApp, переместите в нее файл index.html и измените функцию index . Функция index будет ссылаться на новый путь к шаблону, HelloDjangoApp/index.html. Затем запустите проект, убедитесь, что страница отображается должным образом и остановите сервер.
Зафиксируйте изменения в системе управления версиями и обновите удаленный репозиторий при необходимости, как описано в шаге 2.2.
Вопрос. Следует ли хранить шаблоны страницы в отдельном файле?
Ответ. Обычно шаблоны хранятся в отдельных HTML-файлах. Также можно использовать встроенный шаблон. Чтобы сохранить четкое разделение между разметкой и кодом, рекомендуется использовать отдельный файл.
Вопрос. Следует ли использовать в шаблонах расширение файлов HTML?
Ответ. Использовать расширение HTML для файлов шаблона страницы совсем необязательно, так как вы всегда определяете точный относительный путь к файлу во втором аргументе функции render . Однако Visual Studio (и другие редакторы) предоставляет такие функции, как завершение кода или разметка синтаксиса, для файлов HTML, что значительно важнее того, что шаблоны страниц не имеют строгого формата HTML.
На самом деле, при работе с проектом Django Visual Studio автоматически обнаруживает, что HTML-файл, который вы редактируете, фактически является шаблоном Django, и предоставляет определенные функции автоматического завершения. Например, когда вы начинаете вводить комментарий шаблона страницы Django, . В командах Закомментировать выделенный фрагмент и Раскомментировать выделенный фрагмент (в меню Изменить > Дополнительно или на панели инструментов) также используются комментарии шаблона, а не HTML.
Вопрос. При запуске проекта отображается ошибка, указывающая, что шаблон не найден. В чем проблема?
Вопрос. Почему организация пространства имен шаблона важна?
Ответ. Когда платформа Django выполняет поиск шаблона, на который ссылается функция render , она использует первый найденный файл, который соответствует относительному пути. Если у вас есть несколько приложений Django в одном проекте, использующих одну структуру папок для шаблонов, скорее всего, одно приложение будет непреднамеренно использовать шаблон из другого приложения. Чтобы избежать подобных ошибок, всегда создавайте вложенную папку в папке templates приложения, которая соответствует имени приложения. Это позволит избежать любого дублирования.
Visual Studio Code is a free source code editor developed my Microsoft. It feels much more lightweight than traditional IDEs, yet its extensions make it versatile enough to handle just about any type of development work, including Python and the Django web framework. This guide shows how to use Visual Studio Code for Django projects.
Installation
Make sure the latest version of Visual Studio Code is installed. Then, install the following (free) extensions:
-
(published by Microsoft) – for full Python language support – for template file source highlighting – for common Django code
- Alternatively, install Djaniero – Django Snippets if you prefer
Reload Visual Studio Code after installation.
This slideshow requires JavaScript.
Editing Code
The VS Code Python editor is really first-class. The syntax highlighting is on point, and the shortcuts are mostly what you’d expect from an IDE. Django template files also show syntax highlighting. The Explorer, which shows the project directory structure on the left, may be toggled on and off using the top-left file icon. Check out Python with Visual Studio Code for more features.
This slideshow requires JavaScript.
Virtual Environments
Virtual environments with venv or virtualenv make it easy to manage Python versions and packages locally rather than globally (system-wide). A common best practice is to create a virtual environment for each Python project and install only the packages the project needs via pip. Different environments make it possible to develop projects with different version requirements on the same machine.
Visual Studio Code allows users to configure Python environments. Navigate to File > Preferences > Settings and set the python.pythonPath setting to the path of the desired Python executable. Set it as a Workspace Setting instead of a User Setting if the virtual environment will be specific to the project.
Python virtual environment setup is shown as a Workspace Setting. The terminal window shows the creation and activation of the virtual environment, too.
Helpful Settings
Visual Studio Code settings can be configured to automatically lint and format code, which is especially helpful for Python. As shown on Ruddra’s Blog, install the following packages:
And then add the following settings:
Editor settings may also be language-specific. For example, to limit automatic formatting to Python files only:
Make sure to set the pylintPath setting to the real path value. Keep in mind that these settings are optional.
Full settings for automatically formatting and linting the Python code.
Running Django Commands
Django development relies heavily on its command-line utility. Django commands can be run from a system terminal, but Visual Studio Code provides an Integrated Terminal within the app. The Integrated Terminal is convenient because it opens right to the project’s root directory. Plus, it’s in the same window as the code. The terminal can be opened from View > Integrated Terminal or using the “Ctrl-`” shortcut.
Running Django commands from within the editor is delightfully convenient.
Debugging
Debugging is another way Visual Studio Code’s Django support shines. The extensions already provide the launch configuration for debugging Django apps! As a bonus, it should already be set to use the Python path given by the python.pythonPath setting (for virtual environments). Simply switch to the Debug view and run the Django configuration. The config can be edited if necessary. Then, set breakpoints at the desired lines of code. The debugger will stop at any breakpoints as the Django app runs while the user interacts with the site.
The Django extensions provide a default debug launch config. Simply set breakpoints and then run the “Django” config to debug!
Version Control
Version control in Visual Studio Code is simple and seamless. Git has become the dominant tool in the industry, but VS Code supports other tools as well. The Source Control view shows all changes and provides options for all actions (like commits, pushes, and pulls). Clicking changed files also opens a diff. For Git, there’s no need to use the command line!
The Source Control view with a diff for a changed file.
Visual Studio Code creates a hidden “.vscode” directory in the project root directory for settings and launch configurations. Typically, these settings are specific to a user’s preferences and should be kept to the local workspace only. Remember to exclude them from the Git repository by adding the “.vscode” directory to the .gitignore file.
.gitignore setting for the .vscode directory
Editor Comparisons
JetBrains PyCharm is one of the most popular Python IDEs available today. Its Python and Django development features are top-notch: full code completion, template linking and debugging, a manage.py console, and more. PyCharm also includes support for other Python web frameworks, JavaScript frameworks, and database connections. Django features, however, are available only in the (paid) licensed Professional Edition. It is possible to develop Django apps in the free Community Edition, as detailed in Django Projects in PyCharm Community Edition, but the missing features are a significant limitation. Plus, being a full IDE, PyCharm can feel heavy with its load time and myriad of options.
PyCharm is one of the best overall Python IDEs/editors, but there are other good ones out there. PyDev is an Eclipse-based IDE that provides Django support for free. Sublime Text and Atom also have plugins for Django. Visual Studio Code is nevertheless a viable option. It feels fast and simple yet powerful. Here’s my recommended decision table:
What’s Going On | What You Should Do |
---|---|
Do you already have a PyCharm license? | Just use PyCharm Professional Edition. |
Will you work on a large-scale Django project? | Strongly consider buying the license. |
Do you need something fast, simple, and with basic Django support for free? | Use Visual Studio Code, Atom, or Sublime Text. |
Do you really want to stick to a full IDE for free? | Pick PyDev if you like Eclipse, or follow the guide for Django Projects in PyCharm Community Edition |
Open terminal and navigate to the folder where the code base must be created.
Type code . to open vscode.
In vscode terminal,
Creating a virtual environment:
A virtual environment for a project is essential so that the changes to the configuration files and the installation of packages are confined to that project or environment only and does not affect the local installation files of the system.
python -m venv env1 | makes a virtual environment with name env1 and venv is the python module that makes it.
To activate the environment in linux:
source env1/bin/activate
env1\Scripts\activate.bat
In windows vscode will sometimes give this error “execution of scripts is disabled on this system”
To resolve this type the following in terminal:
Set-ExecutionPolicy RemoteSigned
Set it back to restricted by:
Set-ExecutionPolicy Restricted
after this the console prompt will denote the environment name at its beginning.
To deactivate the environment :
deactivate
In the same terminal:
pip install django | to install django.
python -m django version | to check django version (-m stands for module), pip is also a module and can also be written as py -m pip install django.
django-admin startproject example | to create a project named example
This is an organization unit that contains settings and database configuration information for one or more apps or sites within it.
This can also be created by just creating project folder and copying all the configuration but django makes it much easier to create it.
After running this command django will make some skeleton files required to create the project which are common in all projects.
cd example | change directory and enter example/
This contains a file called manage.py which is essentially a settings and configuration file used by python to do multiple task as followed.
python manage.py startapp myapp | to make a new folder called myapp and populate it with all required skeleton files.
Although this creates the required skeleton files for the app we need to create a urls.py and a directory called template inside the apps folder. This reason for this will be explained further.
python manage.py migrate | to sync and migrate the internal django database which is sqlite by default (django has an internal database management system but it can also work with a variety of databases such as Mysql, Postgres sql etc ).
This is a part of internal management done by django to make sure that the database used by django internally is consistent with the definitions that we have for it.
The internal database management does more than just provide data to apps, it’s also how the built in django user management system works.
python manage.py runserver | to start django webserver (django has its own webserver)
This will fireup the django webserver on localhost:8000 OR 127.0.0.1:8000 (this can be configured later to forward on another ip/url but that is beyond the scope of this article.)
django follows MVT (Model View Template) method of file structure which is similar to the MVC (Model View Controller) method but with some differences.
As stated previously the “startapp” command will create all required files to run the app including views.py and model.py and the user created urls.py with the /template directory.
views.py | contains the logic of the application.
model.py | contains the database (incase of internal django database) and its connections.
The django internal database schema can be written with a simple class where the name of the class is the database name and its attributes are the tables and their fields with its character type, limit and other properties.
urls.py | contains the url mapping for all the pages.
This mapping must be made in the /myapp/urls.py as well as /example/urls.py
/template/base.html, home.html…and so on | contains the html pages that must display the content to user. Here base.html must contain the bootstrap/css files which can be extended to other html files.
First the app must be registered with the project to use its database.
To do this open settings.py in the project folder and add the name of your app to the installed apps list.
Next we need to register the tables we created with the django admin system so that we can manage the database directly from the django admin page.
To do this edit admin.py in the app folder and insert a reference (import the class name) to our newly created table.
python manage.py makemigrations myapp | to sync the models defined in our /myapp/models.py with the database of the project and make a new folder called migrations.
Note: this command is different from python manage.py migrate as this command just sync the internal database with the project and makemigrations will sync the models.py with the database itself.
this is a description on how to change the database we have now (which does not have any models in it) to sync the models defined in our /myapp/models.py
Each set of changes that are made to database are recorded in a separate sequentially numbered file so that migration will be smoother whenever schema changes.
To apply the changes,
python manage.py sqlmigrate myapp 0001 | this will apply the changes in schema of the database of mentioned app following the instructions written in the file number from migrations folder.
python manage.py migrate myapp | to sync all the specified changes to project’s database.
To make an administrative user for the database:
python manage.py createsuperuser | this will ask the username, email id and password and make a admin user for the database.
Whenever any changes are made make sure to rerun python manage.py runserver to refresh the changes.
Читайте также: