Cara menggunakan close application python

In this article, we will see how to create a countdown timer using Python. The code will take input from the user regarding the length of the countdown in seconds. After that, a countdown will begin on the screen of the format ‘minutes: seconds’. We will use the time module here.

Approach

In this project, we will be using the time module and its sleep() function. Follow the below steps to create a countdown timer:

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.

Prerequisites

To successfully complete this Django tutorial, you must do the following (which are the same steps as in the general Python tutorial):

  1. Install the Python extension.

  2. 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 python manage.py migrate 6 in the terminal.
    • (macOS) An installation through Homebrew on macOS using python manage.py migrate 7 (the system install of Python on macOS is not supported).
    • (All operating systems) A download from Anaconda (for data science purposes).
  3. On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running python manage.py migrate 8 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 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 .

  1. On your file system, create a project folder for this tutorial, such as python manage.py migrate 9.

  2. In that folder, use the following command (as appropriate to your computer) to create a virtual environment named Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 0 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 Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 1 from an Anaconda installation, you see an error because the ensurepip module isn't available, and the environment is left in an unfinished state.

  3. Open the project folder in VS Code by running Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 2, or by running VS Code and using the File > Open Folder command.

  4. In VS Code, open the Command Palette (View > Command Palette or (⇧⌘P (Windows, Linux Ctrl+Shift+P))). Then select the Python: Select Interpreter command:

  5. 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 Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 3 or Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 4:

  6. 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 Shell to set "Command Prompt" or "Git Bash" as your default instead.

  7. 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:

  8. Update pip in the virtual environment by running the following command in the VS Code Terminal:

    python -m pip install --upgrade pip
  9. 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 Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 5 (Linux/macOS) or Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 6 (Windows). You know the environment is activated when the command prompt shows (.venv) at the beginning.

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, Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 7, which is installed when you install the Django package.

Create the Django project

  1. In the VS Code Terminal where your virtual environment is activated, run the following command:

    django-admin startproject web_project .

    This Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 8 command assumes (by use of Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //127.0.0.1:8000/ Quit the server with CTRL-BREAK. 9 at the end) that the current folder is your project folder, and creates the following within it:

    • python manage.py startapp hello 0: The Django command-line administrative utility for the project. You run administrative commands for the project using python manage.py startapp hello 1.

    • A subfolder named python manage.py startapp hello 2, which contains the following files:

      • python manage.py startapp hello 3: an empty file that tells Python that this folder is a Python package.
      • python manage.py startapp hello 4: 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.
      • python manage.py startapp hello 5: contains settings for Django project, which you modify in the course of developing a web app.
      • python manage.py startapp hello 6: contains a table of contents for the Django project, which you also modify in the course of development.
      • python manage.py startapp hello 7: 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.
  2. 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 python manage.py startapp hello 8 that is intended for development purposes, but can be used in production for low-volume web apps. For additional information about databases, see the section.

  3. To verify the Django project, make sure your virtual environment is activated, then start Django's development server using the command python manage.py startapp hello 9. The server runs on the default port 8000, and you see output like the following output in the terminal window:

    Performing system checks... System check identified no issues (0 silenced). January 15, 2021 - 14:33:31 Django version 3.1.5, using settings 'web_project.settings' Starting development server at //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 python manage.py startapp hello 7 and python manage.py startapp hello 4 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 from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 2.

  4. Ctrl+click the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 3 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.

  5. 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

  1. In the VS Code Terminal with your virtual environment activated, run the administrative utility's from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 4 command in your project folder (where python manage.py startapp hello 0 resides):

    python manage.py startapp hello

    The command creates a folder called from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6 that contains a number of code files and one subfolder. Of these, you frequently work with from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7 (that contains the functions that define pages in your web app) and from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8 (that contains classes defining your data objects). The from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 9 folder is used by Django's administrative utility to manage database versions as discussed later in this tutorial. There are also the files from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 0 (app configuration), from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 1 (for creating an administrative interface), and from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 2 (for creating tests), which are not covered here.

  2. Modify from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 3 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!")
  3. Create a file, from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 4, with the contents below. The python manage.py startapp hello 6 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 (from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 6) to the from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 7 function that you just added to from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 3:

    from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ]
  4. The python manage.py startapp hello 2 folder also contains a python manage.py startapp hello 6 file, which is where URL routing is actually handled. Open from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 1 and modify it to match the following code (you can retain the instructive comments if you like). This code pulls in the app's from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 4 using from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 3, 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) ]
  5. Save all modified files.

  6. In the VS Code Terminal, again with the virtual environment activated, run the development server with python manage.py startapp hello 9 and open a browser to from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 3 to see a page that renders "Hello, Django".

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 startapp hello 9 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.

  1. 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 from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 7 file containing debug configurations. VS Code can create that for you if you click on the create a launch.json file link:

  2. Select the link and VS Code will prompt for a debug configuration. Select Django from the dropdown and VS Code will populate a new from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 7 file with a Django run configuration. The from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 7 file contains a number of debugging configurations, each of which is a separate JSON object within the python -m pip install --upgrade pip 00 array.

  3. Scroll down to and examine the configuration with the name "Python: Django":

    python -m pip install --upgrade pip 0

    This configuration tells VS Code to run python -m pip install --upgrade pip 01 using the selected Python interpreter and the arguments in the python -m pip install --upgrade pip 02 list. Launching the VS Code debugger with this configuration, then, is the same as running python manage.py startapp hello 9 in the VS Code Terminal with your activated virtual environment. (You can add a port number like python -m pip install --upgrade pip 04 to python -m pip install --upgrade pip 02 if desired.) The python -m pip install --upgrade pip 06 entry also tells VS Code to enable debugging of Django page templates, which you see later in this tutorial.

  4. Test the configuration by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list (F5):

  5. Ctrl+click the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 3 URL in the terminal output window to open the browser and see that the app is running properly.

  6. 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)).

  7. 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.

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.

  1. In from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), ] 4, add a route to the python -m pip install --upgrade pip 09 list:

    python -m pip install --upgrade pip 1

    The first argument to python manage.py migrate 8 defines a route "hello/" that accepts a variable string called name. The string is passed to the python -m pip install --upgrade pip 11 function specified in the second argument to python manage.py migrate 8.

    URL routes are case-sensitive. For example, the route python -m pip install --upgrade pip 13 is distinct from python -m pip install --upgrade pip 14. If you want the same view function to handle both, define paths for each variant.

  2. Replace the contents of from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7 with the following code to define the python -m pip install --upgrade pip 16 function that you can step through in the debugger:

    python -m pip install --upgrade pip 2

    The python -m pip install --upgrade pip 17 variable defined in the URL route is given as an argument to the python -m pip install --upgrade pip 16 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.)

  3. Set a breakpoint at the first line of code in the python -m pip install --upgrade pip 16 function (python -m pip install --upgrade pip 20) 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:

  4. 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.

  5. Output appears in a "Python Debug Console" terminal. Open a browser and navigate to python -m pip install --upgrade pip 21. 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.

  6. Use Step Over to run the python -m pip install --upgrade pip 20 statement.

  7. On the left side of the VS Code window, you see a Variables pane that shows local variables, such as python -m pip install --upgrade pip 23, as well as arguments, such as python -m pip install --upgrade pip 17. 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 python -m pip install --upgrade pip 23, 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.

  8. 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 python -m pip install --upgrade pip 20, you might experiment with different date/time formats. In the editor, select the code that reads python -m pip install --upgrade pip 27, then right-click and select Debug: Evaluate to send that code to the debug console, where it runs:

    python -m pip install --upgrade pip 3

    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.

  9. Copy that line into the > prompt at the bottom of the debug console, and try changing the formatting:

    python -m pip install --upgrade pip 4
  10. 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:

  11. Change the line in the code to use different datetime format, for example python -m pip install --upgrade pip 28, 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.

  12. 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 python -m pip install --upgrade pip 21, output that URL using a python -m pip install --upgrade pip 30 statement somewhere in a file like from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7. The URL appears in the VS Code Terminal where you can use Ctrl+click to open it in a browser.

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 from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, right-click on python -m pip install --upgrade pip 33 in the python -m pip install --upgrade pip 34 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.

Use a template to render a page

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 python -m pip install --upgrade pip 16 function of this tutorial, for example, one might think to format the output in code with something like python -m pip install --upgrade pip 36, where the result in python -m pip install --upgrade pip 37 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 python -m pip install --upgrade pip 38 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.

  1. In the python -m pip install --upgrade pip 39 file, locate the python -m pip install --upgrade pip 40 list and add the following entry, which makes sure the project knows about the app so it can handle templating:

    python -m pip install --upgrade pip 5
  2. Inside the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6 folder, create a folder named python -m pip install --upgrade pip 42, and then another subfolder named from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6 to match the app name (this two-tiered folder structure is typical Django convention).

  3. In the python -m pip install --upgrade pip 44 folder, create a file named python -m pip install --upgrade pip 45 with the contents below. This template contains two placeholders for data values named "name", and "date", which are delineated by pairs of curly braces, python -m pip install --upgrade pip 46 and python -m pip install --upgrade pip 47. All other invariant text is part of the template, along with formatting markup (such as python -m pip install --upgrade pip 48). As you can see, template placeholders can also include formatting, the expressions after the pipe python -m pip install --upgrade pip 49 symbols, in this case using Django's built-in and . The code, then needs only to pass the datetime value rather than a pre-formatted string:

    python -m pip install --upgrade pip 6
  4. At the top of from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, add the following import statement:

    python -m pip install --upgrade pip 7
  5. Also in from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, modify the python -m pip install --upgrade pip 16 function to use python -m pip install --upgrade pip 53 method to load a template and to provide the template context. The context is the set of variables for use within the template. The python -m pip install --upgrade pip 54 function takes the request object, followed by the path to to the template relative to the python -m pip install --upgrade pip 42 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.)

    python -m pip install --upgrade pip 8

    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.

  6. 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.

  7. Also try navigating to a /hello/name URL using a name like python -m pip install --upgrade pip 56 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.

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 python -m pip install --upgrade pip 40 list in python manage.py startapp hello 5 contains python -m pip install --upgrade pip 59, 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 python manage.py startapp hello 5, set python -m pip install --upgrade pip 61, and change python -m pip install --upgrade pip 62 to allow specific hosts. This may result in additional work when using containers. For details, see Issue 13.

Ready the app for static files

  1. In the project's from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 1, add the following python -m pip install --upgrade pip 64 statement:

    python -m pip install --upgrade pip 9
  2. In that same file, add the following line at the end, which includes standard static file URLs to the list that the project recognizes:

    python -m pip install django 0

Refer to static files in a template

  1. In the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6 folder, create a folder named python -m pip install --upgrade pip 66.

  2. Within the python -m pip install --upgrade pip 66 folder, create a subfolder named from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6, 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 python -m pip install --upgrade pip 69 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.

  3. In the python -m pip install --upgrade pip 69 folder, create a file named python -m pip install --upgrade pip 71 with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview.

    python -m pip install django 1
  4. In python -m pip install --upgrade pip 72, add the following lines after the python -m pip install --upgrade pip 73 element. The python -m pip install --upgrade pip 74 tag is a custom Django template tag set, which allows you to use python -m pip install --upgrade pip 75 to refer to a file like the stylesheet.

    python -m pip install django 2
  5. Also in python -m pip install --upgrade pip 72, replace the contents python -m pip install --upgrade pip 77 element with the following markup that uses the python -m pip install --upgrade pip 78 style instead of a python -m pip install --upgrade pip 48 tag:

    python -m pip install django 3
  6. 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 -m pip install --upgrade pip 80 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.

  1. In python -m pip install --upgrade pip 39, add the following line that defines a location where static files are collected when you use the python -m pip install --upgrade pip 82 command:

    python -m pip install django 4
  2. In the Terminal, run the command python -m pip install --upgrade pip 80 and observe that python -m pip install --upgrade pip 84 is copied into the top level python -m pip install --upgrade pip 85 folder alongside python manage.py startapp hello 0.

  3. In practice, run python -m pip install --upgrade pip 82 any time you change static files and before deploying into production.

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 python -m pip install --upgrade pip 88 and python -m pip install --upgrade pip 89 in both the base template and extended templates.

The following steps demonstrate creating a base template.

  1. In the python -m pip install --upgrade pip 44 folder, create a file named python -m pip install --upgrade pip 91 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 python -m pip install --upgrade pip 92 tag to refer to other pages through the names of the corresponding URL patterns rather than by relative path.

    python -m pip install django 5
  2. Add the following styles to python -m pip install --upgrade pip 93 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.)

    python -m pip install django 6

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 python -m pip install --upgrade pip 91, 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.

  1. In VS Code, select the File (Windows/Linux) or Code (macOS), menu, then select Preferences > User snippets.

  2. 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.)

  3. After VS code opens python -m pip install --upgrade pip 95, add the code below within the existing curly braces. (The explanatory comments, not shown here, describe details such as how the python -m pip install --upgrade pip 96 line indicates where VS Code places the cursor after inserting a snippet):

    python -m pip install django 7
  4. Save the python -m pip install --upgrade pip 95 file (⌘S (Windows, Linux Ctrl+S)).

  5. Now, whenever you start typing the snippet's prefix, such as python -m pip install --upgrade pip 98, 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.

  1. In the python -m pip install --upgrade pip 44 folder, create a new file named python -m pip install django 00, Then start typing python -m pip install --upgrade pip 98 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:

  2. At the insertion point in the "title" block, write python -m pip install django 02, and in the "content" block, write python -m pip install django 03, then save the file. These lines are the only unique parts of the extended page template:

  3. In the python -m pip install --upgrade pip 44 folder, create python -m pip install django 05, use the snippet to insert the boilerplate markup, insert python -m pip install django 06 and python -m pip install django 07 in the "title" and "content" blocks, respectively, then save the file.

  4. Repeat the previous step to create python -m pip install django 08 using python -m pip install django 09 and python -m pip install django 10.

  5. In the app's python manage.py startapp hello 6, add routes for the /about and /contact pages. Be mindful that the python -m pip install --upgrade pip 17 argument to the python manage.py migrate 8 function defines the name with which you refer to the page in the python -m pip install --upgrade pip 92 tags in the templates.

    python -m pip install django 8
  6. In from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, add functions for the /about and /contact routes that refer to their respective page templates. Also modify the python -m pip install --upgrade pip 34 function to use the python -m pip install django 00 template.

    python -m pip install django 9

Run the app

With all the page templates in place, save from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, 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.

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 python -m pip install django 19, that represents a specific database object, typically a table. You place these classes in an app's from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8 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:

  1. Make changes to the models in your from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8 file.
  2. Run python -m pip install django 22 to generate scripts in the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 9 folder that migrate the database from its current state to the new state.
  3. Run python -m pip install django 24 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 from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8, 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 . This utility is often used to initialize a data set after the python -m pip install django 26 command has initialized the schema.

When using the python manage.py startapp hello 8 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 python -m pip install django 28, then run python -m pip install django 26.

Types of databases

By default, Django includes a python manage.py startapp hello 8 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 . 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 python -m pip install django 31, which you place in the app's from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8 file. In the database, each model is automatically given a unique ID field named python -m pip install django 33. All other fields are defined as properties of the class using types from python -m pip install django 34 such as python -m pip install django 35 (limited text), python -m pip install django 36 (unlimited text), python -m pip install django 37, python -m pip install django 38, python -m pip install django 39, python -m pip install django 40, python -m pip install django 41. python -m pip install django 42, python -m pip install django 43, and python -m pip install django 44, among others. (See the Model field reference in the Django documentation for details.)

Each field takes some attributes, like python -m pip install django 45. The python -m pip install django 46 attribute means the field is optional; python -m pip install django 47 means that a value is optional. There is also a python -m pip install django 48 attribute that limits values to values in an array of data value/display value tuples.

For example, add the following class in from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8 to define a data model that represents dated entries in a simple message log:

django-admin startproject web_project . 0

A model class can include methods that return values computed from other class properties. Models typically include a python -m pip install django 50 method that returns a string representation of the instance.

Migrate the database

Because you changed your data models by editing from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 8, 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:

django-admin startproject web_project . 1

Take a look in the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 9 folder to see the scripts that python -m pip install django 28 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.

  1. In the from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 6 folder (where you have from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7), create a new file named python -m pip install django 56 with the following code, which defines a Django form that contains a field drawn from the data model, python -m pip install django 57:

    django-admin startproject web_project . 2
  2. In the python -m pip install --upgrade pip 44 folder, create a new template named python -m pip install django 59 with the following contents, which assumes that the template is given a variable named python -m pip install django 60 to define the body of the form. It then adds a submit button with the label "Log".

    django-admin startproject web_project . 3

    Note: Django's python -m pip install django 61 tag provides protection from cross-site request forgeries. See Cross Site Request Forgery protection in the Django documentation for details.

  3. In the app's python -m pip install --upgrade pip 93 file, add a rule to make the input form wider:

    django-admin startproject web_project . 4
  4. In the app's python manage.py startapp hello 6 file, add a route for the new page:

    django-admin startproject web_project . 5
  5. In from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, define the view named python -m pip install django 65 (as referred to by the URL route). This view handles both HTTP GET and POST cases. In the GET case (the python -m pip install django 66 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 (python -m pip install --upgrade pip 78), sets the timestamp, then saves that object at which point it's written to the database:

    django-admin startproject web_project . 6
  6. One more step before you're ready to try everything out! In python -m pip install django 68, add a link in the "navbar" div for the message logging page:

    django-admin startproject web_project . 7
  7. 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:

  8. 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.

  9. Stop the app when you're done.

  10. Now modify the home page to display the logged messages. Start by replacing the contents of app's python -m pip install django 69 file with the markup below. This template expects a context variable named python -m pip install django 70. If it receives one (checked with the python -m pip install django 71 tag), it then iterates over that list (the python -m pip install django 72 tag) to generate table rows for each message. Otherwise the page indicates that no messages have yet been logged.

    django-admin startproject web_project . 8
  11. In python -m pip install --upgrade pip 93, add a rule to format the table a little:

    django-admin startproject web_project . 9
  12. In from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, import Django's generic python -m pip install django 75 class, which we'll use to implement the home page:

    python manage.py migrate 0
  13. Also in from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") 7, replace the python -m pip install --upgrade pip 34 function with a class named python -m pip install django 78, derived from python -m pip install django 75, which ties itself to the python -m pip install django 57 model and implements a function python -m pip install django 81 to generate the context for the template.

    python manage.py migrate 1
  14. In the app's python manage.py startapp hello 6, import the data model:

    python manage.py migrate 2
  15. Also in python manage.py startapp hello 6, make a variable for the new view, which retrieves the five most recent python -m pip install django 57 objects in descending order (meaning that it queries the database), and then provides a name for the data in the template context (python -m pip install django 70), and identifies the template to use:

    python manage.py migrate 3
  16. In python manage.py startapp hello 6, modify the path to the home page to use the python -m pip install django 87 variable:

    python manage.py migrate 4
  17. Start the app and open a browser to the home page, which should now display messages:

  18. Stop the app when you're done.

Use the debugger with page templates

As shown in the previous section, page templates can contain procedural directives like python -m pip install django 72 and python -m pip install django 71, rather than only passive, declarative elements like python -m pip install --upgrade pip 92 and python -m pip install django 91. 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 python -m pip install --upgrade pip 06 in the debugging configuration (as you do already). The following steps demonstrate this capability:

  1. In python -m pip install django 69, set breakpoints on both the python -m pip install django 71 and python -m pip install django 72 lines, as indicated by the yellow arrows in the image below:

  2. 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 python -m pip install django 96 statement and shows all the context variables in the Variables pane:

  3. 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 python -m pip install django 72 loops lets you examine each value in python -m pip install --upgrade pip 78 and lets you step to lines like python -m pip install django 99.

  4. You can also work with variables in the Debug Console panel. (Django filters like django-admin startproject web_project . 00, however, are not presently available in the console.)

  5. 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.

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 django-admin startproject web_project . 01 file.

Although you can create the file by hand, you can also use the django-admin startproject web_project . 02 command to generate the file based on the exact libraries installed in the activated environment:

  1. 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.

  2. In the terminal, run django-admin startproject web_project . 03 to create the django-admin startproject web_project . 01 file in your project folder.

Anyone (or any build server) that receives a copy of the project needs only to run the django-admin startproject web_project . 05 command to reinstall the packages on which the app depends within the active environment.

Note: django-admin startproject web_project . 02 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 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-admin startproject web_project . 07 app, which is included by default in the project's python -m pip install --upgrade pip 40 list (python manage.py startapp hello 5), and authentication is handled with the built-in django-admin startproject web_project . 10 app, which is also in python -m pip install --upgrade pip 40 by default.

Perform the following steps to enable the administrative interface:

  1. Create a superuser account in the app by opening a Terminal in VS Code for your virtual environment, then running the command django-admin startproject web_project . 12, replacing django-admin startproject web_project . 13 and django-admin startproject web_project . 14, 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.

  2. Add the following URL route in the project-level python manage.py startapp hello 6 (from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("hello.urls")), path('admin/', admin.site.urls) ] 1 in this tutorial) to point to the built-in administrative interface:

    python manage.py migrate 5
  3. Run the server, then open a browser to the app's /admin page (such as django-admin startproject web_project . 17 when using the development server).

  4. A login page appears, courtesy of django-admin startproject web_project . 10. Enter your superuser credentials.

  5. 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 django-admin startproject web_project . 19 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.

Postingan terbaru

LIHAT SEMUA