The app you’ve created so far in this tutorial generates only plain text web pages from Python code. Although it’s possible to generate HTML directly in code, developers avoid such a practice because it opens the app to cross-site scripting (XSS) attacks. In the
hello_there
function of this tutorial, for example, one might think to format the output in code with something like
content = "
Hello there, " + clean_name + "!
"
, where the result in
content
is given directly to a browser. This opening allows an attacker to place malicious HTML, including JavaScript code, in the URL that ends up in
clean_name
and thus ends up being run in the browser.
A much better practice is to keep HTML out of your code entirely by using templates, so that your code is concerned only with data values and not with rendering.
In Django, a template is an HTML file that contains placeholders for values that the code provides at run time. The Django templating engine then takes care of making the substitutions when rendering the page, and provides automatic escaping to prevent XSS attacks (that is, if you tried using HTML in a data value, you would see the HTML rendered only as plain text). The code, therefore, concerns itself only with data values and the template concerns itself only with markup. Django templates provide flexible options such as template inheritance, which allows you to define a base page with common markup and then build upon that base with page-specific additions.
In this section, you start by creating a single page using a template. In subsequent sections, you configure the app to serve static files and then create multiple pages to the app that each contains a nav bar from a base template. Django templates also support control flow and iteration, as you see later in this tutorial in the context of template debugging.
In the
web_project/settings.py
file, locate the
INSTALLED_APPS
list and add the following entry, which makes sure the project knows about the app so it can handle templating:
'hello',
Inside the
hello
folder, create a folder named
templates
, and then another subfolder named
hello
to match the app name (this two-tiered folder structure is typical Django convention).
In the
templates/hello
folder, create a file named
hello_there.html
with the contents below. This template contains two placeholders for data values named “name”, and “date”, which are delineated by pairs of curly braces,
{{
and
}}
. All other invariant text is part of the template, along with formatting markup (such as). As you can see, template placeholders can also include formatting, the expressions after the pipesymbols, in this case using Django’s built-in date filter and time filter. The code, then needs only to pass the datetime value rather than a pre-formatted string:
Hello, Django
Hello there, {{ name }}!
It's {{ date | date:"l, d F, Y" }} at {{ date | time:"H:i:s" }}
At the top of
views.py
, add the following import statement:
from django.shortcuts import render
Also in
views.py
, modify the
hello_there
function to use
django.shortcuts.render
method to load a template and to provide the template context. The context is the set of variables for use within the template. The
render
function takes the request object, followed by the path to to the template relative to the
templates
folder, then the context object. (Developers typically name the templates the same as the functions that use them, but matching names are not required because you always refer to the exact filename in your code.)
def hello_there(request, name): print(request.build_absolute_uri()) #optional return render( request, 'hello/hello_there.html', { 'name': name, 'date': datetime.now() } )
You can see that the code is now much simpler, and concerned only with data values, because the markup and formatting is all contained in the template.
Start the program (inside or outside of the debugger, using ⌃F5 (Windows, Linux Ctrl+F5)), navigate to a /hello/name URL, and observe the results.
Also try navigating to a /hello/name URL using a name like
to see Django’s automatic escaping at work. The “name” value shows up as plain text in the browser rather than as rendering an actual element.
Prerequisites
To successfully complete this Django tutorial, you must do the following (which are the same steps as in the general Python tutorial):
Install the Python extension.
Install a version of Python 3 (for which this tutorial is written). Options include:
(All operating systems) A download from python.org; typically use the Download Python 3.9.1 button that appears first on the page (or whatever is the latest version).
(Linux) The built-in Python 3 installation works well, but to install other Python packages you must run
sudo apt install python3-pip
in the terminal.
(macOS) An installation through Homebrew on macOS using
brew install python3
(the system install of Python on macOS is not supported).
(All operating systems) A download from Anaconda (for data science purposes).
On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running
path
at the command prompt. If the Python interpreter’s folder isn’t included, open Windows Settings, search for “environment”, select Edit environment variables for your account, then edit the Path variable to include that folder.
Create and run a minimal Django app
In Django terminology, a “Django project” is composed of several site-level configuration files, along with one or more “apps” that you deploy to a web host to create a full web application. A Django project can contain multiple apps, each of which typically has an independent function in the project, and the same app can be in multiple Django projects. An app, for its part, is just a Python package that follows certain conventions that Django expects.
To create a minimal Django app, then, it’s necessary to first create the Django project to serve as the container for the app, then create the app itself. For both purposes, you use the Django administrative utility,
django-admin
, which is installed when you install the Django package.
Create the Django project
In the VS Code Terminal where your virtual environment is activated, run the following command:
django-admin startproject web_project .
This
startproject
command assumes (by use ofat the end) that the current folder is your project folder, and creates the following within it:
manage.py
: The Django command-line administrative utility for the project. You run administrative commands for the project using
python manage.py [options]
.
A subfolder named
web_project
, which contains the following files:
__init__.py
: an empty file that tells Python that this folder is a Python package.
asgi.py
: an entry point for ASGI-compatible web servers to serve your project. You typically leave this file as-is as it provides the hooks for production web servers.
settings.py
: contains settings for Django project, which you modify in the course of developing a web app.
urls.py
: contains a table of contents for the Django project, which you also modify in the course of development.
wsgi.py
: an entry point for WSGI-compatible web servers to serve your project. You typically leave this file as-is as it provides the hooks for production web servers.
Create an empty development database by running the following command:
python manage.py migrate
When you run the server the first time, it creates a default SQLite database in the file
db.sqlite3
that is intended for development purposes, but can be used in production for low-volume web apps. For additional information about databases, see the Types of databases section.
To verify the Django project, make sure your virtual environment is activated, then start Django’s development server using the command
python manage.py runserver
. The server runs on the default port 8000, and you see output like the following output in the terminal window:
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 13, 2023 - 18:38:07 Django version 4.2.2, using settings 'web_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
Django’s built-in web server is intended only for local development purposes. When you deploy to a web host, however, Django uses the host’s web server instead. The
wsgi.py
and
asgi.py
modules in the Django project take care of hooking into the production servers.
If you want to use a different port than the default 8000, specify the port number on the command line, such as
python manage.py runserver 5000
.
Ctrl+click the
http://127.0.0.1:8000/
URL in the terminal output window to open your default browser to that address. If Django is installed correctly and the project is valid, you see the default page shown below. The VS Code terminal output window also shows the server log.
When you’re done, close the browser window and stop the server in VS Code using Ctrl+C as indicated in the terminal output window.
Create a Django app
In the VS Code Terminal with your virtual environment activated, run the administrative utility’s
startapp
command in your project folder (where
manage.py
resides):
python manage.py startapp hello
The command creates a folder called
hello
that contains a number of code files and one subfolder. Of these, you frequently work with
views.py
(that contains the functions that define pages in your web app) and
models.py
(that contains classes defining your data objects). The
migrations
folder is used by Django’s administrative utility to manage database versions as discussed later in this tutorial. There are also the files
apps.py
(app configuration),
admin.py
(for creating an administrative interface), and
tests.py
(for creating tests), which are not covered here.
Modify
hello/views.py
to match the following code, which creates a single view for the app’s home page:
from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!")
Create a file,
hello/urls.py
, with the contents below. The
urls.py
file is where you specify patterns to route different URLs to their appropriate views. The code below contains one route to map root URL of the app (
""
) to the
views.home
function that you just added to
hello/views.py
:
from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ]
The
web_project
folder also contains a
urls.py
file, which is where URL routing is actually handled. Open
web_project/urls.py
and modify it to match the following code (you can retain the instructive comments if you like). This code pulls in the app’s
hello/urls.py
using
django.urls.include
, which keeps the app’s routes contained within the app. This separation is helpful when a project contains multiple apps.
from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ]
Save all modified files.
In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver
and open a browser to
http://127.0.0.1:8000/
to see a page that renders “Hello, Django”.
Features
Go to definition in templates
Ctrl+click (cmd+click on MacOS) or press F12 on the template path in a
include
or
extends
tag
to jump to this template
Snippets
Support for selected text (when inserting snippet from the menu)
Support for copied text
No unnecessary new lines
Improved syntax
Adds the filetype
django-html
Adds the filetype
django-txt
for email templates.
Better syntax with more operators and default keywords:
Known default tags and filters
Known templatetags namespace from contrib in the {% load %} tag
Known keywords in tags, like:
as
,
asvar
,
with
,
trimmed
…
Syntax highlighting everywhere in your HTML document:
In the HTML tag itself”
In the id, class or any attribute
In inline CSS or Javascript code
Step 1-5: Run the empty Django project
In Visual Studio, select Debug > Start Debugging (F5) or use the Web Server button on the toolbar (the browser you see might vary):
Running the server means to run the command
manage.py runserver
, which starts Django’s built-in development server. If Visual Studio says Failed to start debugger with a message about having no startup file, right-click manage.py in Solution Explorer and select Set as Startup File.
When you start the server, you see a console window opens that also displays the server log. Visual Studio automatically opens a browser to
http://localhost:
. Since the Django project has no apps, Django shows only a default page to confirm that what you have so far is working fine.
When you’re done, stop the server by closing the console window, or by using the Debug > Stop Debugging command in Visual Studio.
Question: Is Django a web server and a framework?
Answer: Yes and no. Django has a built-in web server that’s used for development purposes. This web server is used when you run the web app locally, such as when debugging in Visual Studio. When you deploy to a web host, however, Django uses the host’s web server instead. The wsgi.py module in the Django project takes care of hooking into the production servers.
Answer: In addition to the Debug menu commands and toolbar buttons, you can also launch the server using the Python > Run server or Python > Run debug server commands on the project’s context menu. Both commands open a console window in which you’ll see the local URL (localhost:port) for the running server. However, you must manually open a browser with that URL, and running the debug server doesn’t automatically start the Visual Studio debugger. If you want, you can attach a debugger to the running process by using the Debug > Attach to Process command.
Create a debugger launch profile
You’re probably already wondering if there’s an easier way to run the server and test the app without typing
python manage.py runserver
each time. Fortunately, there is! You can create a customized launch profile in VS Code, which is also used for the inevitable exercise of debugging.
Switch to Run view in VS Code (using the left-side activity bar or F5). You may see the message “To customize Run and Debug create a launch.json file”. This means that you don’t yet have a
launch.json
file containing debug configurations. VS Code can create that for you if you click on the create a launch.json file link:
Select the link and VS Code will prompt for a debug configuration. Select Django from the dropdown and VS Code will populate a new
launch.json
file with a Django run configuration. The
launch.json
file contains a number of debugging configurations, each of which is a separate JSON object within the
configuration
array.
Scroll down to and examine the configuration with the name “Python: Django”:
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": ["runserver"], "django": true, "justMyCode": true } ] }
This configuration tells VS Code to run
"${workspaceFolder}/manage.py"
using the selected Python interpreter and the arguments in the
args
list. Launching the VS Code debugger with this configuration, then, is the same as running
python manage.py runserver
in the VS Code Terminal with your activated virtual environment. (You can add a port number like
"5000"
to
args
if desired.) The
"django": true
entry also tells VS Code to enable debugging of Django page templates, which you see later in this tutorial.
Test the configuration by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list (F5):
Ctrl+click the
http://127.0.0.1:8000/
URL in the terminal output window to open the browser and see that the app is running properly.
Close the browser and stop the debugger when you’re finished. To stop the debugger, use the Stop toolbar button (the red square) or the Run > Stop Debugging command (⇧F5 (Windows, Linux Shift+F5)).
You can now use the Run > Start Debugging at any time to test the app, which also has the benefit of automatically saving all modified files.
Prerequisites
Visual Studio 2017 or later on Windows with the following options:
The Python development workload (Workload tab in the installer). For instructions, see Install Python support in Visual Studio.
Git for Windows and GitHub Extension for Visual Studio on the Individual components tab under Code tools.
Visual Studio 2022 on Windows with the following options:
The Python development workload (Workload tab in the installer). For more instructions, see Install Python support in Visual Studio.
Git for Windows on the Individual components tab under Code tools.
Django project templates also include earlier versions of Python Tools for Visual Studio. The template details might differ from what’s discussed in this tutorial (especially different with earlier versions of the Django framework).
Python development isn’t presently supported in Visual Studio for Mac. On Mac and Linux, use the Python extension in Visual Studio Code.
“Visual Studio projects” and “Django projects”
In Django terminology, a “Django project” has several site-level configuration files along with one or more “apps.” To create a full web application, you can deploy these apps to a web host. A Django project can contain multiple apps, and the same app can be in multiple Django projects.
A Visual Studio project can contain the Django project along with multiple apps. Whenever this tutorial refers to just a “project,” it’s referring to the Visual Studio project. When it refers to the “Django project” portion of the web application, it’s referring to a “Django project” specifically.
Over the course of this tutorial, you’ll create a single Visual Studio solution that contains three separate Django projects. Each project contains a single Django app. You can easily switch between different files for comparison, by keeping the projects in the same solution.
Running The Django Server From VS Code
Having set up your Django project, it’s time to run the Django server from within Visual Studio Code. Running the server from VS Code allows you to leverage the editor’s features, such as debugging and terminal integration, enhancing your development workflow.
Opening The Terminal In VS Code
Start by opening the integrated terminal in Visual Studio Code. You can do this by selecting
View > Terminal
or using the shortcut
Ctrl+
(Windows/Linux) or
Cmd+
# Opening the integrated terminal in VS Code # This terminal allows you to run commands directly from the editor echo "Integrated terminal is open"
Navigating To The Project Directory
In the terminal, navigate to your Django project directory. Use the
cd
command followed by the path to your project directory to change the current working directory.
# Navigating to the Django project directory # Replace 'path_to_your_project' with the actual path to your Django project cd path_to_your_project
Starting The Server From VS Code
Now, start the Django development server by running the following command in the terminal. This command will start the server on the default port 8000.
# Starting the Django development server from VS Code # The server will start on the default port 8000 python manage.py runserver
The server will be accessible at
http://127.0.0.1:8000/in your web browser.
Viewing The Running Application
With the server running, open your web browser and navigate to the server’s URL. You should see the Django welcome page, indicating that the server is running successfully.
# Viewing the running Django application # The Django welcome page should be displayed in your web browser print("Django application is running at http://127.0.0.1:8000/")
Stopping The Server
When you are done working, don’t forget to stop the Django server. You can do this by pressing
Ctrl+C
in the terminal where the server is running.
# Stopping the Django development server # Use Ctrl+C to stop the server when you are done working echo "Server is stopped"
By running the Django server from Visual Studio Code, you integrate your development environment, making it easier to build, test, and debug your Django applications.
Challenge:
John, a seasoned developer, faced challenges integrating Django into his Visual Studio Code (VS Code) environment. The manual configuration was tedious, and he sought a more efficient setup process to enhance his development workflow.
John explored the capabilities of VS Code and discovered the integrated terminal and debugging features. He configured the
launch.jsonfile to streamline the debugging settings:
With the optimized setup, John experienced a significant boost in development efficiency. The integrated tools in VS Code enabled him to run, debug, and troubleshoot Django applications seamlessly, leading to faster development cycles and higher-quality software.
Cách chạy web lên localhost
Bây giờ ta sẽ mở terminal trong Project lên, ta có thể dùng VS Code để mở Terminal:
Bây giờ ta sẽ gõ cú pháp sau để khởi động server ảo
python manage.py runserver
Theo như CMD thông báo thì trang web của sẽ chạy ở localhost cổng 8000, ta sẽ mở trình duyệt truy cập vào localhost:8000 để xem kết quả
Nếu bạn bị xung đột cổng hay muốn đổi cổng. Có thể sử dụng lệnh sau để chạy trang web trên cổng khác:
python manage.py runserver
Ví dụ: chạy python manage.py runserver 8080 để khởi động web ở cổng 8080
Contributing
Issues
Something odd? New feature request?
Please create an issue on Github.
Setup
git clone https://github.com/vscode-django/vscode-django
cd vscode-django
npm install
code .
It’s better to have TSlint installed.
Launching the extension debugger
Make sure you have this snippet in
.vscode/launch.json
, add a rule to format the table a little:
.message_list th,td { text-align: left; padding-right: 15px; }
In
views.py
, import Django’s generic
ListView
class, which we’ll use to implement the home page:
from django.views.generic import ListView
Also in
views.py
, replace the
home
function with a class named
HomeListView
, derived from
ListView
, which ties itself to the
LogMessage
model and implements a function
get_context_data
to generate the context for the template.
# Remove the old home function if you want; it's no longer used class HomeListView(ListView): """Renders the home page, with a list of all messages.""" model = LogMessage def get_context_data(self, **kwargs): context = super(HomeListView, self).get_context_data(**kwargs) return context
In the app’s
urls.py
, import the data model:
from hello.models import LogMessage
Also in
urls.py
, make a variable for the new view, which retrieves the five most recent
LogMessage
objects in descending order (meaning that it queries the database), and then provides a name for the data in the template context (
message_list
), and identifies the template to use:
home_list_view = views.HomeListView.as_view( queryset=LogMessage.objects.order_by("-log_date")[:5], # :5 limits the results to the five most recent context_object_name="message_list", template_name="hello/home.html", )
In
urls.py
, modify the path to the home page to use the
home_list_view
variable:
# Replace the existing path for "" path("", home_list_view, name="home"),
Start the app and open a browser to the home page, which should now display messages:
Stop the app when you’re done.
Feedback
Submit and view feedback for
Setting up Django in Visual Studio Code can streamline your development process, offering a seamless and efficient coding experience. This guide is here to walk you through each step, ensuring you can get started with Django development swiftly and without hassle. Whether you’re a beginner or an experienced developer, you’ll find this setup process straightforward.
Cấu trúc Project Django
Bây giờ ta sẽ tìm hiểu cấu trúc của Project Django. Ta có thể dùng Visual Studio Code để xem cấu trúc rõ ràng hơn:
Trong Project Python sẽ có 1 file manage.py và 1 folder cùng tên với Project. File manage.py giúp ta tương tác Project qua các command (như là tạo tài khoản admin, tạo database, chạy server ảo, …), vì vậy không nên chỉnh sửa ở đây.
Ở folder PythonWeb gồm có 4 file sau:
__init__.py: đây là 1 file cơ bản trong Python dùng để biến folder chứa nó thành package, giúp tao có thể import
setttings.py: đây là file cấu hình project. (VD: cấu hình database, đặt múi giờ, cài thêm thư viện, …)
urls.py: đây là file giúp chúng ta tạo các đường dẫn urls của trang web để liên kết các webpage lại với nhau
wsgi.py: đây là file giúp chúng ta deploy project lên server
Frequently Asked Questions
Can I Use Different Python Versions for Different Django Projects in VS Code?
Yes, you can specify a different Python interpreter for each Django project by selecting the appropriate interpreter in the lower-left corner of the VS Code window or by modifying the
pythonPath
in the project’s
settings.json
file.
How Can I Change the Default Port When Running the Django Server in VS Code?
You can change the default port by modifying the
args
parameter in the
launch.json
file. Replace
"runserver"
with
"runserver
, replacing with the port number you wish to use.
How Do I Resolve “Module Not Found” Errors When Importing Django in VS Code?
Ensure that you have activated the correct virtual environment and that Django is installed in it. You can activate the virtual environment in the integrated terminal and use the
pip list
command to verify the installed packages.
What Should I Do If Breakpoints Are Not Triggered During Debugging in VS Code?
Verify that the
launch.json
file is correctly configured and that you are running the application in debug mode. Additionally, ensure that the
"django": true
setting is present in the
launch.json
configuration for Django debugging.
How Can I Improve the Performance of the Django Development Server Running in VS Code?
Consider disabling the auto-reload feature by adding the
--noreload
flag when starting the server. Additionally, closing unused applications and increasing system resources can also contribute to improved performance.
Let’s test your knowledge!
Django extension for Visual Studio Code
Beautiful syntax and scoped snippets for perfectionists with deadlines
Serve static files
Static files are pieces of content that your web app returns as-is for certain requests, such as CSS files. Serving static files requires that the
INSTALLED_APPS
list in
settings.py
contains
django.contrib.staticfiles
, which is included by default.
Serving static files in Django is something of an art, especially when deploying to production. What’s shown here is a simple approach that works with the Django development server and also a production server like Gunicorn. A full treatment of static files, however, is beyond the scope of this tutorial, so for more information, see Managing static files in the Django documentation.
When switching to production, navigate to
settings.py
, set
DEBUG=False
, and change
ALLOWED_HOSTS = ['*']
to allow specific hosts. This may result in additional work when using containers. For details, see Issue 13.
Ready the app for static files
In the project’s
web_project/urls.py
, add the following
import
statement:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
In that same file, add the following line at the end, which includes standard static file URLs to the list that the project recognizes:
urlpatterns += staticfiles_urlpatterns()
Refer to static files in a template
In the
hello
folder, create a folder named
static
.
Within the
static
folder, create a subfolder named
hello
, matching the app name.
The reason for this extra subfolder is that when you deploy the Django project to a production server, you collect all the static files into a single folder that’s then served by a dedicated static file server. The
static/hello
subfolder ensures that when the app’s static files are collected, they’re in an app-specific subfolder and won’t collide with file from other apps in the same project.
In the
static/hello
folder, create a file named
site.css
with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview.
.message { font-weight: 600; color: blue; }
In
templates/hello/hello_there.html
, add the following lines after theelement. The
{% load static %}
tag is a custom Django template tag set, which allows you to use
{% static %}
to refer to a file like the stylesheet.
{% load static %}
Also in
templates/hello/hello_there.html
, replace the contentselement with the following markup that uses the
message
style instead of atag:
Hello, there {{ name }}!
It's {{ date | date:'l, d F, Y' }} at {{ date | time:'H:i:s' }}.
Run the app, navigate to a /hello/name URL, and observe that the message renders in blue. Stop the app when you’re done.
Use the collectstatic command
For production deployments, you typically collect all the static files from your apps into a single folder using the
python manage.py collectstatic
command. You can then use a dedicated static file server to serve those files, which typically results in better overall performance. The following steps show how this collection is made, although you don’t use the collection when running with the Django development server.
In
web_project/settings.py
, add the following line that defines a location where static files are collected when you use the
collectstatic
any time you change static files and before deploying into production.
Installing Django
With Visual Studio Code set up, the next step is to install Django. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. 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.
Installing Python
Before installing Django, ensure that Python is installed on your system. Django is a Python framework, so this is a prerequisite. You can download the latest version of Python from the official website.
# Checking Python version # This command will display the installed Python version import sys print(sys.version)
Installing Django Using Pip
Once Python is installed, you can install Django using pip, which is the package installer for Python. Open the terminal in Visual Studio Code by selecting
View > Terminal
, and type the following command:
# Installing Django # This command will download and install the latest Django version pip install django
Ensure that the installation process completes without errors.
Verifying Django Installation
After installing Django, it’s good practice to verify that the installation was successful. You can do this by running the following command in the terminal:
# Verifying Django installation # This command will display the installed Django version import django print(django.get_version())
This confirmation is crucial to ensure that you are working with the right version and that Django is ready for use.
Creating A Virtual Environment
It’s recommended to create a virtual environment for your Django projects. A virtual environment is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
# Creating a virtual environment # This command will create a new virtual environment in the current directory python -m venv myenv
myenv\Scripts\activate, and on Mac/Linux, use
source myenv/bin/activate. With the virtual environment activated, you can install packages locally for this project, isolating them from the global Python installation.
With Django installed and the virtual environment set up, you are now ready to start building your Django applications in Visual Studio Code.
Optional activities
The following sections describe additional steps that you might find helpful in your work with Python and Visual Studio Code.
Create a requirements.txt file for the environment
When you share your app code through source control or some other means, it doesn’t make sense to copy all the files in a virtual environment because recipients can always recreate that environment themselves.
Accordingly, developers typically omit the virtual environment folder from source control and instead describe the app’s dependencies using a
requirements.txt
file.
Although you can create the file by hand, you can also use the
pip freeze
command to generate the file based on the exact libraries installed in the activated environment:
With your chosen environment selected using the Python: Select Interpreter command, run the Terminal: Create New Terminal command (⌃⇧` (Windows, Linux Ctrl+Shift+`))) to open a terminal with that environment activated.
In the terminal, run
pip freeze > requirements.txt
to create the
requirements.txt
file in your project folder.
Anyone (or any build server) that receives a copy of the project needs only to run the
pip install -r requirements.txt
command to reinstall the packages on which the app depends within the active environment.
Note:
pip freeze
lists all the Python packages you have installed in the current environment, including packages you aren’t currently using. The command also lists packages with exact version numbers, which you might want to convert to ranges for more flexibility in the future. For more information, see Requirements Files in the pip command documentation.
Create a superuser and enable the administrative interface
By default, Django provides an administrative interface for a web app that’s protected by authentication. The interface is implemented through the built-in
django.contrib.admin
app, which is included by default in the project’s
INSTALLED_APPS
list (
settings.py
), and authentication is handled with the built-in
django.contrib.auth
app, which is also in
INSTALLED_APPS
by default.
Perform the following steps to enable the administrative interface:
Create a superuser account in the app by opening a Terminal in VS Code for your virtual environment, then running the command
, replacingand, of course, with your personal information. When you run the command, Django prompts you to enter and confirm your password.
Be sure to remember your username and password combination. These are the credentials you use to authenticate with the app.
Add the following URL route in the project-level
urls.py
(
web_project/urls.py
in this tutorial) to point to the built-in administrative interface:
# This path is included by default when creating the app path("admin/", admin.site.urls),
Run the server, then open a browser to the app’s /admin page (such as
http://127.0.0.1:8000/admin
when using the development server).
A login page appears, courtesy of
django.contrib.auth
. Enter your superuser credentials.
Once you’re authenticated, you see the default administration page, through which you can manage users and groups:
You can customize the administrative interface as much as you like. For example, you could provide capabilities to edit and remove entries in the database. For more information on making customizations, refer to the Django admin site documentation.
Create a container for a Django app using the Docker extension
The Docker extension makes it easy to build, manage, and deploy containerized applications from Visual Studio Code. If you’re interested in learning how to create a Python container for the Django app developed in this tutorial, check out the Python in a container tutorial, which will walk you through how to:
Create a
Dockerfile
file describing a simple Python container.
Build, run, and verify the functionality of a Django app.
Debug the app running in a container.
Next steps
Congratulations on completing this walkthrough of working with Django in Visual Studio Code!
The completed code project from this tutorial can be found on GitHub: python-sample-vscode-django-tutorial.
In this tutorial, we’ve only scratched the surface of everything Django can do. Be sure to visit the Django documentation and the official Django tutorial for many more details on views, templates, data models, URL routing, the administrative interface, using other kinds of databases, deployment to production, and more.
To try your app on a production website, check out the tutorial Deploy Python apps to Azure App Service using Docker Containers. Azure also offers a standard container, App Service on Linux, to which you deploy web apps from within VS Code.
You may also want to review the following articles in the VS Code docs that are relevant to Python:
Tạo Project Python Django
Nội dung
Để theo dõi bài này tốt nhất, bạn nên có kiến thức về:
PYTHON CƠ BẢN
HTML – CSS – JS
Xem qua nội dung bài SƠ LƯỢC VỀ PYTHON DJANGO
Bài này sẽ giới thiệu những nội dung sau:
Cách tạo 1 Project Django thông qua CMD
Cấu trúc Project Django
Cách chạy web trên Local Host
Step 1-1: Create a Visual Studio project and solution
When working with Django from the command line, you usually start a project by running the
django-admin startproject
command. In Visual Studio, the “Blank Django Web Project” template provides the same structure within a Visual Studio project and solution.
In Visual Studio, select File > New > Project, search for “Django”, and select the Blank Django Web Project template. (You can also find the template under Python > Web in the left-hand list.)
In the fields at the bottom of the dialog, enter the following information (as shown in the previous graphic), then select OK:
Name: set the name of the Visual Studio project to BasicProject. This name is also used for the Django project.
Location: specify a location in which to create the Visual Studio solution and project.
Solution: leave this control set to default Create new solution option.
Solution name: set to LearningDjango, which is appropriate for the solution as a container for multiple projects in this tutorial.
Create directory for solution: Leave set (the default).
Create new Git repository: Select this option (which is clear by default) so that Visual Studio creates a local Git repository when it creates the solution. If you don’t see this option, run the Visual Studio installer and add the Git for Windows and GitHub Extension for Visual Studio on the Individual components tab under Code tools.
After a moment, Visual Studio prompts you with a dialog saying This project requires external packages (shown below). This dialog appears because the template includes a requirements.txt file referencing the latest Django 1.x package. (Select Show required packages to see the exact dependencies.)
Select the option I will install them myself. You create the virtual environment shortly to make sure it’s excluded from source control. (You can always create the environment from requirements.txt.)
In Visual Studio, select File > New > Project, search for “Django”, and select the Blank Django Web Project template, then select Next.
Enter the following information and then select Create:
Project Name: Set the name of the Visual Studio project to BasicProject. This name is also used for the Django project.
Location: Specify a location in which to create the Visual Studio solution and project.
Solution: Leave this control set to default Create new solution option.
Solution name: Set to LearningDjango, which is appropriate for the solution as a container for multiple projects in this tutorial.
Configuring Django Environment In VS Code
Now that Django is installed, the next step is configuring the Django environment within Visual Studio Code. Proper configuration is essential to leverage the full capabilities of both Django and VS Code, ensuring a smooth and efficient development experience.
Setting Up The Workspace
Start by setting up a workspace for your Django project in VS Code. A workspace contains the project files, settings, and extensions. Open VS Code, go to
File > Add Folder to Workspace
, and select the folder where your Django project is located.
# Setting up workspace # The workspace should contain your Django project files print("Workspace is set up")
This setup allows easy navigation and management of your project files.
Configuring Django Settings
Next, configure the Django settings for your project. Open the
settings.py
file in your Django project and adjust the settings as needed. Pay special attention to the
DEBUG
,
ALLOWED_HOSTS
, and
DATABASES
settings.
# Configuring Django settings # Adjust the settings according to your project requirements DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "db.sqlite3", } }
Refer to the Django documentation for detailed information on each setting.
Configuring Debugging
Configuring debugging is a vital step to troubleshoot and optimize your Django application. In VS Code, create a
launch.json
file by going to the Run view, clicking on the gear icon, and selecting
Django
. This action will generate a configuration file tailored for Django projects.
// Configuring debugging for Django // This JSON configuration is for debugging Django applications in VS Code { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true } ] }
Activating Virtual Environment
Lastly, ensure that the virtual environment for your project is activated in VS Code. In the terminal, run the activation command specific to your operating system. Once activated, the virtual environment’s name will appear on the left side of the terminal prompt.
# Activating virtual environment # Use the appropriate activation command for your OS # Windows: myenv\Scripts\activate # Mac/Linux: source myenv/bin/activate
With these configurations in place, your Django environment in Visual Studio Code is fully set up, and you’re ready to start developing and debugging Django applications efficiently.
Create a project environment for the Django tutorial
In this section, you create a virtual environment in which Django is installed. Using a virtual environment avoids installing Django into a global Python environment and gives you exact control over the libraries used in an application. A virtual environment also makes it easy to Create a requirements.txt file for the environment.
On your file system, create a project folder for this tutorial, such as
hello_django
.
In that folder, use the following command (as appropriate to your computer) to create a virtual environment named
.venv
based on your current interpreter:
# Linux sudo apt-get install python3-venv # If needed python3 -m venv .venv source .venv/bin/activate # macOS python3 -m venv .venv source .venv/bin/activate # Windows py -3 -m venv .venv .venv\scripts\activate
Note: Use a stock Python installation when running the above commands. If you use
python.exe
from an Anaconda installation, you see an error because the ensurepip module isn’t available, and the environment is left in an unfinished state.
Open the project folder in VS Code by running
code .
, or by running VS Code and using the File > Open Folder command.
In VS Code, open the Command Palette (View > Command Palette or (⇧⌘P (Windows, Linux Ctrl+Shift+P))). Then select the Python: Select Interpreter command:
The command presents a list of available interpreters that VS Code can locate automatically (your list will vary; if you don’t see the desired interpreter, see Configuring Python environments). From the list, select the virtual environment in your project folder that starts with
./.venv
or
.\.venv
:
Run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
Note: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run activate.ps1 because running scripts is disabled on the system. The error provides a link for information on how to allow scripts. Otherwise, use Terminal: Select Default Profile to set “Command Prompt” or “Git Bash” as your default instead.
The selected environment appears on the right side of the VS Code status bar, and notices the (‘.venv’: venv) indicator that tells you that you’re using a virtual environment:
Update pip in the virtual environment by running the following command in the VS Code Terminal:
python -m pip install --upgrade pip
Install Django in the virtual environment by running the following command in the VS Code Terminal:
python -m pip install django
You now have a self-contained environment ready for writing Django code. VS Code activates the environment automatically when you use Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)). If you open a separate command prompt or terminal, activate the environment by running
source .venv/bin/activate
(Linux/macOS) or
.venv\Scripts\Activate.ps1
(Windows). You know the environment is activated when the command prompt shows (.venv) at the beginning.
Explore the debugger
Debugging gives you the opportunity to pause a running program on a particular line of code. When a program is paused, you can examine variables, run code in the Debug Console panel, and otherwise take advantage of the features described on Debugging. Running the debugger also automatically saves any modified files before the debugging session begins.
Before you begin: Make sure you’ve stopped the running app at the end of the last section by using Ctrl+C in the terminal. If you leave the app running in one terminal, it continues to own the port. As a result, when you run the app in the debugger using the same port, the original running app handles all the requests and you won’t see any activity in the app being debugged and the program won’t stop at breakpoints. In other words, if the debugger doesn’t seem to be working, make sure that no other instance of the app is still running.
defines a route “hello/” that accepts a variable string called name. The string is passed to the
views.hello_there
function specified in the second argument to
path
.
URL routes are case-sensitive. For example, the route
/hello/
is distinct from
/Hello/
. If you want the same view function to handle both, define paths for each variant.
Replace the contents of
views.py
with the following code to define the
hello_there
function that you can step through in the debugger:
import re from django.utils.timezone import datetime from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") def hello_there(request, name): now = datetime.now() formatted_now = now.strftime("%A, %d %B, %Y at %X") # Filter the name argument to letters only using regular expressions. URL arguments # can contain arbitrary text, so we restrict to safe characters only. match_object = re.match("[a-zA-Z]+", name) if match_object: clean_name = match_object.group(0) else: clean_name = "Friend" content = "Hello there, " + clean_name + "! It's " + formatted_now return HttpResponse(content)
The
name
variable defined in the URL route is given as an argument to the
hello_there
function. As described in the code comments, always filter arbitrary user-provided information to avoid various attacks on your app. In this case, the code filters the name argument to contain only letters, which avoids injection of control characters, HTML, and so forth. (When you use templates in the next section, Django does automatic filtering and you don’t need this code.)
Set a breakpoint at the first line of code in the
hello_there
function (
now = datetime.now()
) by doing any one of the following:
With the cursor on that line, press F9, or,
With the cursor on that line, select the Run > Toggle Breakpoint menu command, or,
Click directly in the margin to the left of the line number (a faded red dot appears when hovering there).
The breakpoint appears as a red dot in the left margin:
Start the debugger by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list (F5):
Observe that the status bar changes color to indicate debugging:
A debugging toolbar (shown below) also appears in VS Code containing commands in the following order: Pause (or 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)). See VS Code debugging for a description of each command.
Output appears in a “Python Debug Console” terminal. Open a browser and navigate to
http://127.0.0.1:8000/hello/VSCode
. Before the page renders, VS Code pauses the program at the breakpoint you set. The small yellow arrow on the breakpoint indicates that it’s the next line of code to run.
Use Step Over to run the
now = datetime.now()
statement.
On the left side of the VS Code window, you see a Variables pane that shows local variables, such as
now
, as well as arguments, such as
name
. Below that are panes for Watch, Call Stack, and Breakpoints (see VS Code debugging for details). In the Locals section, try expanding different values. You can also double-click values (or use Enter (Windows, Linux F2)) to modify them. Changing variables such as
now
, however, can break the program. Developers typically make changes only to correct values when the code didn’t produce the right value to begin with.
When a program is paused, the Debug Console panel (which is different from the “Python Debug Console” in the Terminal panel) lets you experiment with expressions and try out bits of code using the current state of the program. For example, once you’ve stepped over the line
now = datetime.now()
, you might experiment with different date/time formats. In the editor, select the code that reads
now.strftime("%A, %d %B, %Y at %X")
, then right-click and select Debug: Evaluate to send that code to the debug console, where it runs:
now.strftime("%A, %d %B, %Y at %X") 'Friday, 07 September, 2018 at 07:46:32'
Tip: The Debug Console also shows exceptions from within the app that may not appear in the terminal. For example, if you see a “Paused on exception” message in the Call Stack area of Run and Debug view, switch to the Debug Console to see the exception message.
Copy that line into the > prompt at the bottom of the debug console, and try changing the formatting:
now.strftime("%A, %d %B, %Y at %X") 'Tuesday, 13 June, 2023 at 18:03:19' now.strftime("%a, %d %b, %Y at %X") 'Tue, 13 Jun, 2023 at 18:03:19' now.strftime("%a, %d %b, %y at %X") 'Tue, 13 Jun, 23 at 18:03:19'
Step through a few more lines of code, if you’d like, then select Continue (F5) to let the program run. The browser window shows the result:
Change the line in the code to use different datetime format, for example
now.strftime("%a, %d %b, %y at %X")
, and then save the file. The Django server will automatically reload, which means the changes will be applied without the need to restart the debugger. Refresh the page on the browser to see the update.
Close the browser and stop the debugger when you’re finished. To stop the debugger, use the Stop toolbar button (the red square) or the Run > Stop Debugging command (⇧F5 (Windows, Linux Shift+F5)).
Tip: To make it easier to repeatedly navigate to a specific URL like
http://127.0.0.1:8000/hello/VSCode
, output that URL using a
views.py
. The URL appears in the VS Code Terminal where you can use Ctrl+click to open it in a browser.
Tải xuống
Tài liệu
Nhằm phục vụ mục đích học tập Offline của cộng đồng, Kteam hỗ trợ tính năng lưu trữ nội dung bài học Tạo Project Python Django dưới dạng file PDF trong link bên dưới.
Ngoài ra, bạn cũng có thể tìm thấy các tài liệu được đóng góp từ cộng đồng ở mục TÀI LIỆU trên thư viện Howkteam.com
Đừng quên like và share để ủng hộ Kteam và tác giả nhé!
Go to Definition and Peek Definition commands
During your work with Django or any other library, you may want to examine the code in those libraries themselves. VS Code provides two convenient commands that navigate directly to the definitions of classes and other objects in any code:
Go to Definition jumps from your code into the code that defines an object. For example, in
views.py
, right-click on
HttpResponse
in the
home
function and select Go to Definition (or use F12), which navigates to the class definition in the Django library.
Peek Definition (⌥F12 (Windows Alt+F12, Linux Ctrl+Shift+F10), also on the right-click context menu), is similar, but displays the class definition directly in the editor (making space in the editor window to avoid obscuring any code). Press Escape to close the Peek window or use the x in the upper right corner.
Setting Up Visual Studio Code
Setting up Visual Studio Code (VS Code) is the first step in your Django development journey. Visual Studio Code is a lightweight but powerful source code editor that runs on your desktop. It comes with built-in support for JavaScript, TypeScript, and Node.js, with additional extensions available for other languages, including Python, which we will be using for Django.
Downloading And Installing VS Code
Start by downloading the latest version of Visual Studio Code from the official website. The installation process is straightforward; simply follow the on-screen instructions. Once installed, open VS Code and familiarize yourself with the user interface.
Installing Python Extension
For Django development, you’ll need the Python extension for Visual Studio Code. To install it, go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window. Search for ‘Python’ in the search bar and install the one published by Microsoft.
# This is a comment in Python code print("Python extension is now installed")
This squiggle indicates that the Python linter is active, helping you catch errors in your code.
Configuring Python Interpreter
Once the Python extension is installed, you need to configure the Python interpreter for your project. Open the Command Palette by pressing
Ctrl+Shift+P
(Windows) or
Cmd+Shift+P
(Mac), and type ‘Python: Select Interpreter’. Choose the Python interpreter that you want to use from the dropdown list.
# Selecting Python interpreter # The interpreter you select will be used for running Python code print("Python interpreter selected")
This setup is essential for working with Django, as it relies on Python.
Installing Essential Extensions
Besides the Python extension, consider installing other helpful extensions to enhance your development experience. Some recommended extensions are Django, Django Template, and Django Snippets. These extensions provide useful snippets, syntax highlighting, and additional features for Django development.
# Installing Django extensions # These extensions will make working with Django more efficient print("Django extensions installed")
Django Tutorial in Visual Studio Code
Django is a high-level Python framework designed for rapid, secure, and scalable web development. Django includes rich support for URL routing, page templates, and working with data.
In this Django tutorial, you create a simple Django app with three pages that use a common base template. You create this app in the context of Visual Studio Code in order to understand how to work with Django in the VS Code terminal, editor, and debugger. This tutorial does not explore various details about Django itself, such as working with data models and creating an administrative interface. For guidance on those aspects, refer to the Django documentation links at the end of this tutorial.
The completed code project from this Django tutorial can be found on GitHub: python-sample-vscode-django-tutorial.
If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.
Debugging Django Applications In VS Code
Debugging is a crucial aspect of the development process, and Visual Studio Code offers robust tools for debugging Django applications. Utilizing VS Code’s debugging features can help you identify and resolve issues more efficiently, enhancing the quality of your applications.
Configuring Debug Settings
To start debugging, you first need to configure the debug settings in VS Code. Open the
.vscode
folder in your project directory and create or edit the
launch.json
file with the following configuration:
// Configuring debug settings for Django // This JSON configuration is tailored for debugging Django applications in VS Code { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true } ] }
Setting Breakpoints
With the debug settings configured, you can set breakpoints in your code. Breakpoints are markers that pause the execution of your application at a specific line of code, allowing you to inspect the program’s state.
# Setting a breakpoint # Click on the left margin next to the line number where you want to set a breakpoint print("Breakpoint is set")
Starting The Debugging Session
Once the breakpoints are set, start the debugging session by clicking on the Run icon in the Activity Bar on the side of the window, then selecting
Run and Debug
. Choose
Django
from the configuration dropdown.
# Starting the debugging session # The execution will pause at the breakpoints, allowing you to inspect the application print("Debugging session has started")
Inspecting Variables And Watching Expressions
While debugging, use the Variables and Watch panels to inspect the values of variables and evaluate expressions. Adding expressions to the Watch panel allows you to monitor their values as you step through the code.
# Inspecting variables and watching expressions # Use the Variables and Watch panels to evaluate the state of your application variable_value = "Inspect me" print(variable_value)
Viewing Debugging Output And Logs
Lastly, check the Debug Console and Terminal panels to view the debugging output and logs. These panels display valuable information and error messages that can aid in troubleshooting.
# Viewing debugging output and logs # The Debug Console and Terminal panels display important information for debugging print("Debugging output is available")
Leveraging the debugging tools in Visual Studio Code will streamline the process of identifying and resolving issues in your Django applications, leading to more stable and reliable software.
Thảo luận
Nếu bạn có bất kỳ khó khăn hay thắc mắc gì về khóa học, đừng ngần ngại đặt câu hỏi trong phần bên dưới hoặc trong mục HỎI & ĐÁP trên thư viện Howkteam.com để nhận được sự hỗ trợ từ cộng đồng.
chào,admin và mọi người cho mình hỏi nếu project có nhiều app có chức năng giống nhau ,thí dụ tạo nhiều app giống app polls ,thế thì urls của project thì ghi
path(‘poll1/’, include(‘poll1.urls’)),
path(‘poll2/’, include(‘poll2.urls’)),
path(‘poll3/’, include(‘poll3.urls’)), làm thế sai 0
chào,admin và mọi người cho mình hỏi nếu project có nhiều app có chức năng giống nhau ,thí dụ tạo nhiều app giống app polls ,thế thì urls của project thì ghi
path(‘poll1/’, include(‘poll1.urls’)),
path(‘poll2/’, include(‘poll2.urls’)),
path(‘poll3/’, include(‘poll3.urls’)),
ghi thế đúng không các bạn
python -m django startproject tên_file
Các bạn có thể dùng câu lệnh này để tạo file nhé
lỗi ‘django-admin’ is not recognized as an internal or external command, operable program or batch file. ạ, ai có teamview hay ultraviewer không sửa giúp tớ với
Tutorial: Get started with the Django web framework in Visual Studio
Django is a high-level Python framework designed for rapid, secure, and scalable web development. This tutorial explores the Django framework in the context of the project templates. Visual Studio provides the project templates to streamline the creation of Django-based web apps.
In this tutorial, you learn how to:
Create a basic Django project in a Git repository using the “Blank Django Web Project” template (step 1).
Create a Django app with one page and render that page using a template (step 2).
Serve static files, add pages, and use template inheritance (step 3).
Use the Django Web Project template to create an app with multiple pages and responsive design (step 4).
Authenticate users (step 5).
Tricks
Gettext and internationalization
Dealing with
django.po
files?
Consider installing the Gettext extension by MrOrz.
Emmet
Add the following item to the Emmet: Include Languages settings:
Item
Value
django-html
html
Step 1-3: Create the virtual environment and exclude it from source control
Now that you’ve configured source control for your project, you can create the virtual environment that contains the necessary Django packages for the project. You can then use Team Explorer to exclude the environment’s folder from source control.
In Solution Explorer, right-click the Python Environments node and select Add Virtual Environment.
An Add Virtual Environment dialog appears, with a message saying We found a requirements.txt file. This message indicates that Visual Studio uses that file to configure the virtual environment.
Select Create to accept the defaults. (You can change the name of the virtual environment if you want, which just changes the name of its subfolder, but
env
is a standard convention.)
Consent to administrator privileges if prompted, then be patient for a few minutes while Visual Studio downloads and installs packages, which for Django means expanding several thousand files in about as many subfolders! You can see progress in the Visual Studio Output window. While you’re waiting, ponder the Question sections that follow.
On the Visual Studio Git controls (on the status bar), select the changes indicator (that shows 99*) which opens the Changes page in Team Explorer.
Creating the virtual environment brought in thousands of changes, but you don’t need to include any of them in source control because you (or anyone else cloning the project) can always recreate the environment from requirements.txt.
To exclude the virtual environment, right-click the env folder and select Ignore these local items.
After excluding the virtual environment, the only remaining changes are to the project file and .gitignore. The .gitignore file contains an added entry for the virtual environment folder. You can double-click the file to see a diff.
Enter a commit message and select the Commit All button, then push the commits to your remote repository.
In Solution Explorer, right-click the Python Environments node and select Add Environment.
Select Create to accept the defaults, in Add Virtual Environment dialog. (You can change the name of the virtual environment if you want, which just changes the name of its subfolder, but
env
is a standard convention.)
Consent to administrator privileges if prompted, then wait a few minutes while Visual Studio downloads and installs packages. During this time, thousands of files are transferred to many subfolders. You can see the progress in the Visual Studio Output window. While you’re waiting, ponder the Question sections that follow.
On the Visual Studio Git controls (on the status bar), select the changes indicator (that shows 99*) which opens the Changes page in Team Explorer.
Creation of the virtual environment brought in thousands of changes, but you don’t need to include any of them in source control because you (or anyone else cloning the project) can always recreate the environment from requirements.txt.
To exclude the virtual environment, right-click the env folder and select Ignore these local items.
After excluding the virtual environment, the only remaining changes are to the project file and .gitignore file. The .gitignore file contains an added entry for the virtual environment folder. You can double-click the file to see a diff.
Enter a commit message and select the Commit All button, then push the commits to your remote repository.
Question: Why do I want to create a virtual environment?
Answer: A virtual environment is a great way to isolate your app’s exact dependencies. Such isolation avoids conflicts within a global Python environment, and aids both testing and collaboration. Over time, as you develop an app, you invariably bring in many helpful Python packages. You can easily update the project’s requirements.txt file by keeping packages in a project-specific virtual environment. The requirements.txt file describes the environment, which is included in the source control. When the project is copied to any other computers, including build servers, deployment servers, and other development computers, it’s easy to recreate the environment using only requirements.txt (which is why the environment doesn’t need to be in source control). For more information, see Use virtual environments.
Question: How do I remove a virtual environment that’s already committed to source control?
Answer: First, edit your .gitignore file to exclude the folder. Find the section at the end with the comment
# Python Tools for Visual Studio (PTVS)
and add a new line for the virtual environment folder, such as
/BasicProject/env
. (Visual Studio doesn’t show the file in Solution Explorer. To open the file directly, go to File > Open > File. You can also open the file from Team Explorer. Go to the Settings page and select Repository Settings. Now, navigate to the Ignore & Attributes Files section and select the Edit link next to .gitignore.)
Second, open a command window, navigate to a folder such as BasicProject. The BasicProject folder contains the virtual environment folder such as env, and run
git rm -r env
. Then commit those changes from the command line (
git commit -m 'Remove venv'
) or commit from the Changes page of Team Explorer.
Step 1-4: Examine the boilerplate code
Once project creation completes, examine the boilerplate Django project code (which is again the same as generated by the CLI command
django-admin startproject
).
The root of your project has manage.py, the Django command-line administrative utility that Visual Studio automatically sets as the project startup file. You run the utility on the command line using
python manage.py [options]
. For common Django tasks, Visual Studio provides convenient menu commands. Right-click the project in Solution Explorer and select Python to see the list. You’ll come across some of these commands in the course of this tutorial.
In your project, there’s a folder with the same name as the project. It contains the basic Django project files:
__init.py: An empty file that tells Python that this folder is a Python package.
settings.py: Contains settings for Django project, which you’ll modify in the course of developing a web app.
urls.py: Contains a table of contents for the Django project, which you’ll also modify in the course of development.
wsgi.py: An entry point for WSGI-compatible web servers to serve your project. You usually leave this file as-is, as it provides the hooks for production web servers.
As noted earlier, the Visual Studio template also adds a requirements.txt file to your project specifying the Django package dependency. The presence of this file is what invites you to create a virtual environment when first creating the project.
Answer: Yes. Expand the Python Environments node, right-click your virtual environment, and select the Generate requirements.txt command. It’s good to use this command periodically as you modify the environment, and commit changes to requirements.txt to source control along with any other code changes that depend on that environment. If you set up continuous integration on a build server, you should generate the file and commit changes whenever you modify the environment.
Creating A Django Project
With the environment configured, you’re ready to create a new Django project. A Django project is the collection of settings and configurations for a specific website, including database configurations, Django-specific options, and application-specific settings.
Creating The Project Structure
Initiate the creation of a new Django project by running the following command in the VS Code terminal. Replace
myproject
with the desired name for your project.
# Creating a new Django project # Replace 'myproject' with your preferred project name django-admin startproject myproject
Navigate into this directory to manage your project.
Understanding The Project Files
Within the newly created project directory, you’ll find several project files and a subdirectory with the same name as the project. These files are essential for the functioning of your Django project.
# Understanding the project files # These files are automatically generated and essential for the project print("manage.py, myproject/__init__.py, myproject/settings.py, myproject/urls.py, myproject/asgi.py, myproject/wsgi.py")
Each file has a specific purpose, detailed in the Django documentation.
Configuring The Database
Django comes with a built-in SQLite database, which is sufficient for development purposes. To configure it, navigate to the
settings.py
file and ensure the
DATABASES
setting is correctly configured.
# Configuring the SQLite database # This configuration is suitable for development purposes DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "db.sqlite3", } }
Running The Initial Migrations
After configuring the database, run the initial migrations to set up the database schema. Migrations are Django’s way of propagating changes made to models into the database schema.
# Running the initial migrations # This command sets up the database schema python manage.py migrate
It’s a vital step to ensure the database is ready for your application.
Starting the Development Server
Finally, start the Django development server to see your project in action. The development server is a lightweight web server provided by Django for development and testing.
# Starting the development server # This command runs the server on the default port 8000 python manage.py runserver
http://127.0.0.1:8000/in your web browser.
With the project created and the development server running, you are now ready to start building your Django applications and exploring the features and functionalities that Django has to offer.
Cách tạo 1 Project Django thông qua CMD
Như ở bài SƠ LƯỢC VỀ PYTHON DJANGO, Kteam đã hướng dẫn cho các bạn tải thư viện Django về. Bây giờ, thông qua thư viện đó, chúng ta sẽ tạo 1 Project như sau:
Bước 1: Vào một thư mục mình muốn lưu Project, mở CMD tại đó lên. Ta có thể gõ cmd tại đường dẫn phía trên để mở CMD của Window
Lúc đó CMD sẽ hiện ra
Bước 2: Ta sẽ dùng cú pháp sau để tạo ra 1 Project Web
django-admin startproject
Lưu ý: Không nên đặt tên là Django hay là Test. Ở đây, mình đặt tên project là PythonWeb
Bây giờ ngay chỗ folder sẽ xuất hiện Project mình vừa tạo
Work with data, data models, and migrations
Many web apps work with information stored in a database, and Django makes it easy to represent the objects in that database using models. In Django, a model is a Python class, derived from
django.db.models.Model
, that represents a specific database object, typically a table. You place these classes in an app’s
models.py
file.
With Django, you work with your database almost exclusively through the models you define in code. Django’s “migrations” then handle all the details of the underlying database automatically as you evolve the models over time. The general workflow is as follows:
Make changes to the models in your
models.py
file.
Run
python manage.py makemigrations
to generate scripts in the
migrations
folder that migrate the database from its current state to the new state.
Run
python manage.py migrate
to apply the scripts to the actual database.
The migration scripts effectively record all the incremental changes you make to your data models over time. By applying the migrations, Django updates the database to match your models. Because each incremental change has its own script, Django can automatically migrate any previous version of a database (including a new database) to the current version. As a result, you need concern yourself only with your models in
models.py
, never with the underlying database schema or the migration scripts. You let Django do that part!
In code, too, you work exclusively with your model classes to store and retrieve data; Django handles the underlying details. The one exception is that you can write data into your database using the Django administrative utility loaddata command. This utility is often used to initialize a data set after the
migrate
command has initialized the schema.
When using the
db.sqlite3
file, you can also work directly with the database using a tool like the SQLite browser. It’s fine to add or delete records in tables using such a tool, but avoid making changes to the database schema because the database will then be out of sync with your app’s models. Instead, change the models, run
makemigrations
, then run
migrate
.
Types of databases
By default, Django includes a
db.sqlite3
file for an app’s database that’s suitable for development work. As described on When to use SQLite (sqlite.org), SQLite works fine for low to medium traffic sites with fewer than 100 K hits/day, but is not recommended for higher volumes. It’s also limited to a single computer, so it cannot be used in any multi-server scenario such as load-balancing and geo-replication.
For these reasons, consider using a production-level data store such as PostgreSQL, MySQL, and SQL Server. For information on Django’s support for other databases, see Database setup. You can also use the Azure SDK for Python to work with Azure storage services like tables and blobs.
Define models
A Django model is again a Python class derived from
django.db.model.Models
, which you place in the app’s
models.py
file. In the database, each model is automatically given a unique ID field named
id
. All other fields are defined as properties of the class using types from
django.db.models
such as
CharField
(limited text),
TextField
(unlimited text),
EmailField
,
URLField
,
IntegerField
,
DecimalField
,
BooleanField
.
DateTimeField
,
ForeignKey
, and
ManyToMany
, among others. (See the Model field reference in the Django documentation for details.)
Each field takes some attributes, like
max_length
. The
blank=True
attribute means the field is optional;
null=true
means that a value is optional. There is also a
choices
attribute that limits values to values in an array of data value/display value tuples.
For example, add the following class in
models.py
to define a data model that represents dated entries in a simple message log:
from django.db import models from django.utils import timezone class LogMessage(models.Model): message = models.CharField(max_length=300) log_date = models.DateTimeField("date logged") def __str__(self): """Returns a string representation of a message.""" date = timezone.localtime(self.log_date) return f"'{self.message}' logged on {date.strftime('%A, %d %B, %Y at %X')}"
A model class can include methods that return values computed from other class properties. Models typically include a
__str__
method that returns a string representation of the instance.
Migrate the database
Because you changed your data models by editing
models.py
, you need to update the database itself. In VS Code, open a Terminal with your virtual environment activated (use the Terminal: Create New Terminal command, ⌃⇧` (Windows, Linux Ctrl+Shift+`))), navigate to the project folder, and run the following commands:
generates. You can also look at the database itself to see that the schema is updated.
If you see errors when running the commands, make sure you’re not using a debugging terminal that’s left over from previous steps, as they may not have the virtual environment activated.
Use the database through the models
With your models in place and the database migrated, you can store and retrieve data using only your models. In this section, you add a form page to the app through which you can log a message. You then modify the home page to display those messages. Because you modify many code files here, be mindful of the details.
In the
hello
folder (where you have
views.py
), create a new file named
forms.py
with the following code, which defines a Django form that contains a field drawn from the data model,
LogMessage
:
from django import forms from hello.models import LogMessage class LogMessageForm(forms.ModelForm): class Meta: model = LogMessage fields = ("message",) # NOTE: the trailing comma is required
In the
templates/hello
folder, create a new template named
log_message.html
with the following contents, which assumes that the template is given a variable named
form
to define the body of the form. It then adds a submit button with the label “Log”.
{% extends "hello/layout.html" %} {% block title %} Log a message {% endblock %} {% block content %}
{% endblock %}
Note: Django’s
{% csrf_token %}
tag provides protection from cross-site request forgeries. See Cross Site Request Forgery protection in the Django documentation for details.
In the app’s
static/hello/site.css
file, add a rule to make the input form wider:
input[name=message] { width: 80%; }
In the app’s
urls.py
file, add a route for the new page:
path("log/", views.log_message, name="log"),
In
views.py
, define the view named
log_message
(as referred to by the URL route). This view handles both HTTP GET and POST cases. In the GET case (the
else:
section), it just displays the form that you defined in the previous steps. In the POST case, it retrieves the data from the form into a data object (
message
), sets the timestamp, then saves that object at which point it’s written to the database:
# Add these to existing imports at the top of the file: from django.shortcuts import redirect from hello.forms import LogMessageForm from hello.models import LogMessage # Add this code elsewhere in the file: def log_message(request): form = LogMessageForm(request.POST or None) if request.method == "POST": if form.is_valid(): message = form.save(commit=False) message.log_date = datetime.now() message.save() return redirect("home") else: return render(request, "hello/log_message.html", {"form": form})
One more step before you’re ready to try everything out! In
templates/hello/layout.html
, add a link in the “navbar” div for the message logging page:
Run the app and open a browser to the home page. Select the Log Message link on the nav bar, which should display the message logging page:
Enter a message, select Log, and you should be taken back to the home page. The home page doesn’t yet show any of the logged messages yet (which you remedy in a moment). Feel free to log a few more messages as well. If you want, peek in the database using a tool like SQLite Browser to see that records have been created. Open the database as read-only, or otherwise remember to close the database before using the app, otherwise the app will fail because the database is locked.
Stop the app when you’re done.
Now modify the home page to display the logged messages. Start by replacing the contents of app’s
templates/hello/home.html
file with the markup below. This template expects a context variable named
message_list
. If it receives one (checked with the
{% if message_list %}
tag), it then iterates over that list (the
{% for message in message_list %}
tag) to generate table rows for each message. Otherwise the page indicates that no messages have yet been logged.
{% extends "hello/layout.html" %} {% block title %} Home {% endblock %} {% block content %}
Use the debugger with page templates
As shown in the previous section, page templates can contain procedural directives like
{% for message in message_list %}
and
{% if message_list %}
, rather than only passive, declarative elements like
{% url %}
and
{% block %}
. As a result, you can have programming errors inside templates as with any other procedural code.
Fortunately, the Python Extension for VS Code provides template debugging when you have
"django": true
in the debugging configuration (as you do already). The following steps demonstrate this capability:
In
templates/hello/home.html
, set breakpoints on both the
{% if message_list %}
and
{% for message in message_list %}
lines, as indicated by the yellow arrows in the image below:
Run the app in the debugger and open a browser to the home page. (If you're already running the debugger, you don't have to restart the app after setting breakpoints; just refresh the page.) Observe that VS Code breaks into the debugger in the template on the
{% if %}
statement and shows all the context variables in the Variables pane:
Use the Step Over (F10) command to step through the template code. Observe that the debugger steps over all declarative statements and pauses at any procedural code. For example, stepping through the
{% for message in message_list %}
loops lets you examine each value in
message
and lets you step to lines like
{{ message.log_date | date:'d M Y' }}
.
You can also work with variables in the Debug Console panel. (Django filters like
date
, however, are not presently available in the console.)
When you're ready, select Continue (F5) to finish running the app and view the rendered page in the browser. Stop the debugger when you're done.
Step 1-2: Examine the Git controls and publish to a remote repository
Because you selected the Create new Git repository in the New Project dialog, the project is already committed to local source control as the creation process completes. In this step, you familiarize yourself with Visual Studio's Git controls and the Team Explorer window in which you work with source control.
Examine the Git controls on the bottom corner of the Visual Studio main window. From left to right, these controls show unpushed commits, uncommitted changes, the name of the repository, and the current branch:
Note
If you don't select the Create new Git repository in the New Project dialog, the Git controls show only an Add to source control command that creates a local repository.
Select the changes button, and Visual Studio opens its Team Explorer window on the Changes page. Because the newly created project is already committed to source control automatically, you don't see any pending changes.
On the Visual Studio status bar, select the unpushed commits button (the up arrow with 2) to open the Synchronization page in Team Explorer. Because you have only a local repository, the page provides easy options to publish the repository to different remote repositories.
You can choose whichever service you want for your own projects. This tutorial shows the use of GitHub, where the completed sample code for the tutorial is maintained in the Microsoft/python-sample-vs-learning-django repository.
When selecting any of the Publish controls, Team Explorer prompts you for more information. For example, when publishing the sample for this tutorial, the repository itself had to be created first, in which case, the Push to Remote Repository option was used with the repository's URL.
If you don't have an existing repository, the Publish to GitHub and Push to Azure DevOps options let you create one directly from within Visual Studio.
As you work through this tutorial, get into the habit of periodically using the controls in Visual Studio to commit and push changes. This tutorial reminds you at appropriate points.
Tip
To quickly navigate within Team Explorer, select the header (that reads Changes or Push in the images above) to see a pop-up menu of the available pages.
In this step, you'll familiarize yourself with Visual Studio's Git controls and Team Explorer. With the Team Explorer window, you'll work with the source control.
To commit the project to your local source control:
Select Add to Source Control command at the bottom corner of the Visual Studio main window.
Then, select the Git option.
Now, you're taken to the Create Git repository window, where you can create and push a new repository.
After creating a repository, a set of new Git controls appears at the bottom. From left to right, these controls show unpushed commits, uncommitted changes, the current branch, and the name of the repository.
Select the Git changes button. Visual Studio then opens the Git Changes page in Team Explorer. You don't see any pending changes as the newly created project is already committed to source control automatically.
On the Visual Studio status bar, select the unpushed commits button (the up arrow with 2) to open the Synchronization page in Team Explorer. The Synchronization page provides easy options to publish the local repository to different remote repositories.
You can choose any service you want for your projects. This tutorial shows the use of GitHub, where the completed sample code for the tutorial is maintained in the Microsoft/python-sample-vs-learning-django repository.
When selecting any of the Publish controls, Team Explorer prompts you for more information. For example, when publishing the sample for this tutorial, the repository itself has to be created first, in which case, the Push to Remote Repository option was used with the repository's URL.
If you don't have an existing repository, the Publish to GitHub and Push to Azure DevOps options let you create one directly from within Visual Studio.
As you work through this tutorial, get into the habit of periodically using the controls in Visual Studio to commit and push changes. This tutorial reminds you at appropriate points.
Tip
To quickly navigate within Team Explorer, select the header (that reads Changes or Push in the images above) to see a pop-up menu of the available pages.
Question: What are some advantages of using source control from the beginning of a project?
Answer: Source control from the start, especially if you also use a remote repository, provides a regular offsite backup of your project. Unlike maintaining a project on a local file system, source control provides a complete change history and the easy ability to revert a single file or the whole project to its previous state. The change history helps determine the cause of regressions (test failures). When multiple people are working on a project, the source control manages the overwrite and provides conflict resolution.
Lastly, source control, which is fundamentally a form of automation, sets you up for automating builds, testing, and release management. It's the first step in using DevOps for a project. There's really no reason to not use source control from the beginning as the barriers to entry are low.
For further discussion on source control as automation, see The Source of Truth: The Role of Repositories in DevOps, an article in MSDN Magazine written for mobile apps that also applies to web apps.
Question: Can I prevent Visual Studio from autocommitting a new project?
Answer: Yes. To disable autocommit, go to the Settings page in Team Explorer. Select Git > Global settings, clear the option labeled Commit changes after merge by default, and then select Update.
Create multiple templates that extend a base template
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates then extend. (This is also called template inheritance, meaning the extended pages inherit elements from the base page.)
Also, because you'll likely create many pages that extend the same template, it's helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.
The following sections walk through different parts of this process.
Create a base page template and styles
A base page template in Django contains all the shared parts of a set of pages, including references to CSS files, script files, and so forth. Base templates also define one or more block tags with content that extended templates are expected to override. A block tag is delineated by
{% block
%}
and
{% endblock %}
in both the base template and extended templates.
The following steps demonstrate creating a base template.
In the
templates/hello
folder, create a file named
layout.html
with the contents below, which contains blocks named "title" and "content". As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you create in a later section. Notice the use of Django's
{% url %}
tag to refer to other pages through the names of the corresponding URL patterns rather than by relative path.
below the existing "message" style, and save the file. (This walkthrough doesn't attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.)
.navbar { background-color: lightslategray; font-size: 1em; font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; color: white; padding: 8px 5px 8px 5px; } .navbar a { text-decoration: none; color: inherit; } .navbar-brand { font-size: 1.2em; font-weight: 600; } .navbar-item { font-variant: small-caps; margin-left: 30px; } .body-content { padding: 5px; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
You can run the app at this point, but because you haven't made use of the base template anywhere and haven't changed any code files, the result is the same as the previous step. Complete the remaining sections to see the final effect.
Create a code snippet
Because the three pages you create in the next section extend
layout.html
, it saves time to create a code snippet to initialize a new template file with the appropriate reference to the base template. A code snippet provides a consistent piece of code from a single source, which avoids errors that can creep in when using copy-paste from existing code.
In VS Code, select the File (Windows/Linux) or Code (macOS), menu, then select Preferences > User snippets.
In the list that appears, select html. (The option may appear as "html.json" in the Existing Snippets section of the list if you've created snippets previously.)
After VS code opens
html.json
, add the code below within the existing curly braces. (The explanatory comments, not shown here, describe details such as how the
$0
line indicates where VS Code places the cursor after inserting a snippet):
"Django Tutorial: template extending layout.html": { "prefix": "djextlayout", "body": [ "{% extends \"hello/layout.html\" %}", "{% block title %}", "$0", "{% endblock %}", "{% block content %}", "{% endblock %}" ], "description": "Boilerplate template that extends layout.html" },
Save the
html.json
file (⌘S (Windows, Linux Ctrl+S)).
Now, whenever you start typing the snippet's prefix, such as
djext
, VS Code provides the snippet as an autocomplete option, as shown in the next section. You can also use the Insert Snippet command to choose a snippet from a menu.
For more information on code snippets in general, refer to Creating snippets.
Use the code snippet to add pages
With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.
In the
templates/hello
folder, create a new file named
home.html
, Then start typing
djext
to see the snippet appear as a completion:
When you select the completion, the snippet's code appears with the cursor on the snippet's insertion point:
At the insertion point in the "title" block, write
Home
, and in the "content" block, write
Home page for the Visual Studio Code Django tutorial.
, then save the file. These lines are the only unique parts of the extended page template:
In the
templates/hello
folder, create
about.html
, use the snippet to insert the boilerplate markup, insert
About us
and
About page for the Visual Studio Code Django tutorial.
in the "title" and "content" blocks, respectively, then save the file.
Repeat the previous step to create
templates/hello/contact.html
using
Contact us
and
Contact page for the Visual Studio Code Django tutorial.
.
In the app's
urls.py
, add routes for the /about and /contact pages. Be mindful that the
name
argument to the
path
function defines the name with which you refer to the page in the
{% url %}
tags in the templates.
path("about/", views.about, name="about"), path("contact/", views.contact, name="contact"),
In
views.py
, add functions for the /about and /contact routes that refer to their respective page templates. Also modify the
home
function to use the
home.html
template.
# Replace the existing home function with the one below def home(request): return render(request, "hello/home.html") def about(request): return render(request, "hello/about.html") def contact(request): return render(request, "hello/contact.html")
Run the app
With all the page templates in place, save
views.py
, run the app, and open a browser to the home page to see the results. Navigate between the pages to verify that the page templates are properly extending the base template.