Back to Python
2026-01-218 min read

Make a Static Website (Python Programming)

Learn Make a Static Website (Python Programming) step by step with clear examples and exercises.

Title: Make a Static Website (Python Programming)


Why This Matters

In today's digital world, having a website is essential for showcasing your work, sharing ideas, or even selling products online. Python, with its simplicity and versatility, is an excellent choice for creating static websites quickly and efficiently. Understanding how to create a static website using Python will equip you with valuable skills that can help you in various aspects of web development.

A static website is a type of web page that has fixed content, meaning the content does not change or interact with users without being updated manually. Static websites are beneficial for individuals and small businesses who want to establish an online presence without the need for complex backend functionality.


Prerequisites

Before diving into the core concept, it's essential to have a basic understanding of:

  1. Python programming language (syntax and data structures)
  2. File handling (reading and writing files)
  3. HTML basics (structure and tags)
  4. Familiarity with web browsers and how they interpret HTML, CSS, and JavaScript
  5. Understanding the difference between static and dynamic websites
  6. Basic understanding of web servers and how they serve web content to users
  7. Knowledge of command line interfaces (CLI) and navigating file systems
  8. Familiarity with version control systems such as Git for managing project files

Core Concept

To create a simple static website using Python, we'll use a library called jinja2. This library allows us to write HTML templates and generate dynamic pages by inserting Python variables into the HTML structure.

First, let's install the required library:

pip install jinja2

Now, create a new directory called my_static_website. Inside this directory, create two subdirectories: templates and static. The templates directory will contain our HTML templates, while the static directory will store the generated HTML files.

Next, create a file called template.html in the templates directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<h1>{% block content %}Welcome to my website!{% endblock %}</h1>
<!-- Add more HTML elements as needed -->
</body>
</html>

In this template, we've defined two blocks: title and content. These blocks will be replaced with dynamic content when generating the HTML pages.

Next, create a Python script called main.py in the root directory (my_static_website) to render the HTML templates:

from jinja2 import Environment, FileSystemLoader
import os

Set the path to your templates directory

template_dir = "templates"

output_dir = "static"

Initialize the Jinja2 environment

env = Environment(loader=FileSystemLoader(template_dir))

Create the output directory if it doesn't exist

if not os.path.exists(output_dir):

os.makedirs(output_dir)

Load the template

template = env.get_template('template.html')

Generate and save the HTML file

for i in range(10):

html = template.render(title="Page {}".format(i + 1), content="This is page number {}.".format(i + 1))

with open(os.path.join(output_dir, "page_{}.html".format(i + 1)), 'w') as f:

f.write(html)


In this script, we've defined the template directory and output directory, initialized the Jinja2 environment, loaded the `template.html`, created an output directory if it doesn't exist, and generated 10 HTML pages with dynamic titles and content.

---

Worked Example

To see how this works in practice, run the following command:

python main.py

This will generate 10 HTML files in the static directory. Open one of them (e.g., static/page_1.html) to verify that it contains the dynamic title and content.


Common Mistakes

  1. Forgetting to install the required library (jinja2)
  2. Not defining the template directory or output directory correctly
  3. Using incorrect syntax when defining blocks in the HTML template
  4. Failing to create the output directory if it doesn't exist
  5. Not properly saving the generated HTML files
  6. Incorrectly specifying the path to the templates directory or output directory in the Python script
  7. Trying to use Jinja2 for dynamic content without handling user input or other dynamic data sources
  8. Overlooking potential security issues when using Jinja2, such as cross-site scripting (XSS) vulnerabilities
  9. Failing to properly escape or sanitize user input before inserting it into the HTML templates
  10. Not testing and debugging the generated HTML pages in various web browsers to ensure compatibility

Common Mistakes - Subheadings

  • Incorrect handling of template blocks
  • Incorrect path definitions for directories and files
  • Ignoring potential security vulnerabilities
  • Failing to properly sanitize user input
  • Overlooking browser compatibility issues
  1. Incorrect Handling of Template Blocks
  • Using the wrong block syntax (e.g., {% set %} instead of {% block %})
  • Forgetting to define a block in the HTML template
  • Not passing the correct values to replace the blocks when rendering the templates
  1. Incorrect Path Definitions for Directories and Files
  • Specifying an incorrect path to the templates directory or output directory
  • Failing to include the trailing slash in the directory paths (e.g., templates/ instead of templates)
  1. Ignoring Potential Security Vulnerabilities
  • Not properly sanitizing user input before inserting it into the HTML templates
  • Allowing users to execute arbitrary code by exploiting security vulnerabilities such as Cross-Site Scripting (XSS) or SQL injection
  1. Failing to Properly Sanitize User Input
  • Not using functions like escape() or safe_string() to sanitize user input before inserting it into the HTML templates
  • Allowing users to inject malicious code or scripts into the website
  1. Overlooking Browser Compatibility Issues
  • Testing the generated HTML pages only in one browser and neglecting to check for compatibility issues in other browsers
  • Using outdated HTML, CSS, or JavaScript features that are not supported by all modern web browsers

Practice Questions

  1. Modify the script to generate 20 HTML pages instead of 10.
  2. Change the title and content blocks in the template to display the current date and time on each page.
  3. Add a navigation menu with links to all generated pages at the top of each HTML file.
  4. Create a form that allows users to enter their name, and display a personalized greeting on the generated pages.
  5. Implement a simple contact form that sends an email when submitted.
  6. Style your static website using CSS and add responsive design for mobile devices.
  7. Add JavaScript interactivity, such as a slideshow or interactive map.
  8. Integrate social media sharing buttons to allow users to share content easily.
  9. Implement search functionality to help users find specific content on the website.
  10. Optimize the generated HTML pages for SEO (search engine optimization) by using proper meta tags, header hierarchy, and keyword usage.

Practice Questions - Subheadings

  1. Generating More Pages
  • Modify the for loop in the Python script to generate 20 HTML pages instead of 10
  1. Displaying Current Date and Time
  • Update the template.html file to include a block for the current date and time, and modify the Python script to pass the current date and time as variables when rendering the templates
  1. Adding a Navigation Menu
  • Create an HTML template for the navigation menu and include it in each generated page
  • Modify the Python script to load the navigation menu template and insert it into each generated HTML file
  1. Personalized Greeting Form
  • Create an HTML form that allows users to enter their name
  • Modify the Python script to extract the user's name from the submitted form data and display a personalized greeting on the generated pages
  1. Simple Contact Form
  • Implement a contact form using an HTML form, email client (e.g., smtplib), and Jinja2 templates
  1. Styling with CSS
  • Create a styles.css file in the templates directory and link it to each generated HTML page
  • Add styles for layout, typography, colors, and other visual elements
  1. Responsive Design
  • Use media queries and flexible grid systems (e.g., Bootstrap) to ensure that your static website looks good on various devices and screen sizes
  1. JavaScript Interactivity
  • Integrate JavaScript libraries such as jQuery or React to add interactive features like a slideshow, accordion, or modal dialog
  1. Social Media Sharing Buttons
  • Use APIs from popular social media platforms (e.g., Facebook, Twitter, LinkedIn) to implement sharing buttons on your static website
  1. SEO Optimization
  • Research and apply best practices for search engine optimization (SEO), such as using relevant keywords, meta tags, header hierarchy, and keyword usage in the HTML templates and content

FAQ

Q: Can I use other templates besides template.html?

A: Yes! You can create as many templates as you need and generate different HTML pages based on them.

Q: How do I style my static website using CSS?

A: You can include a styles.css file in your template and link it to each generated HTML page.

Q: Can I use this approach for creating dynamic websites instead of static ones?

A: While the example provided creates static pages, you can create dynamic content by using Python variables within the Jinja2 templates and handling user input.

Q: How do I handle user input in my static website?

A: You can use various methods to collect user input, such as HTML forms, AJAX requests, or even third-party APIs. Once you have the user input, you can process it and display the results using Jinja2 templates.

Q: How do I ensure my static website is secure?

A: To maintain security, follow best practices such as validating and sanitizing user input, keeping your Python libraries up-to-date, and using HTTPS for encrypted communication between the server and client. Additionally, you can implement CAPTCHAs to prevent automated attacks and limit login attempts to protect against brute force attacks.

Q: How do I optimize my static website for SEO?

A: To improve your website's search engine ranking, focus on using relevant keywords in your content, creating high-quality backlinks, and ensuring proper meta tags, header hierarchy, and keyword usage are implemented. Additionally, you can use tools like Google Search Console to monitor your website's performance and make necessary improvements.

Q: How do I test my static website on various web browsers?

A: You can use browser compatibility testing tools such as BrowserStack or Sauce Labs to test your static website on multiple web browsers and devices.

Q: Can I deploy my static website online?

A: Yes! You can deploy your static website on various hosting platforms like GitHub Pages, Netlify, or Vercel. These platforms offer free hosting for static websites and make it easy to publish your project online.

Make a Static Website (Python Programming) | Python | XQA Learn