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.
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.
To successfully complete this Django tutorial, you must do the following (which are the same steps as in the general Python tutorial):
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 .
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
5 (Linux/macOS) or
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,
7, which is installed when you install the Django package.
Create the Django project
Create a Django app
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
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.
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.
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:
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
16 function of this tutorial, for example, one might think to format the output in code with something like
36, where the result in
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.
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
40 list in
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
61, and change
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
Refer to static files in a template
Use the collectstatic command
For production deployments, you typically collect all the static files from your apps into a single folder using the
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.
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
89 in both the base template and extended templates.
The following steps demonstrate creating a base template.
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
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.
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.
Run the app
With all the page templates in place, save
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
19, that represents a specific database object, typically a table. You place these classes in an app's
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:
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
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
26 command has initialized the schema.
When using the
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
28, then run
Types of databases
By default, Django includes a
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.
A Django model is again a Python class derived from
31, which you place in the app's
8 file. In the database, each model is automatically given a unique ID field named
33. All other fields are defined as properties of the class using types from
34 such as
35 (limited text),
36 (unlimited text),
44, among others. (See the Model field reference in the Django documentation for details.)
Each field takes some attributes, like
46 attribute means the field is optional;
47 means that a value is optional. There is also a
48 attribute that limits values to values in an array of data value/display value tuples.
For example, add the following class in
8 to define a data model that represents dated entries in a simple message log:
A model class can include methods that return values computed from other class properties. Models typically include a
50 method that returns a string representation of the instance.
Migrate the database
Because you changed your data models by editing
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:
Take a look in the
9 folder to see the scripts that
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.
Use the debugger with page templates
As shown in the previous section, page templates can contain procedural directives like
71, rather than only passive, declarative elements like
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
06 in the debugging configuration (as you do already). The following steps demonstrate this capability:
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
Although you can create the file by hand, you can also use the
02 command to generate the file based on the exact libraries installed in the activated environment:
Anyone (or any build server) that receives a copy of the project needs only to run the
05 command to reinstall the packages on which the app depends within the active environment.
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
07 app, which is included by default in the project's
40 list (
5), and authentication is handled with the built-in
10 app, which is also in
40 by default.
Perform the following steps to enable the administrative interface:
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:
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.