Python Script to Django HTML Output

When I started working with Django, one of the key challenges was figuring out how to seamlessly output Python data into HTML templates. Django’s template system is designed to make this easy, but if you’re new to it, things can feel a bit overwhelming.

I’ve refined my approach to rendering Python variables, logic, and data structures into HTML, making my web applications dynamic and user-friendly. In this article, I’ll share my firsthand experience on how to output Python to HTML in Django. I’ll walk you through the core concepts, provide practical examples.

Let’s get in!

Django’s Template System

Django uses its templating language, which allows you to embed Python-like expressions inside HTML files. This system separates your business logic (Python code) from your presentation layer (HTML), which is a best practice for maintainable code.

At its core, Django templates allow you to:

  • Output variables and data passed from views
  • Use control structures like loops and conditionals
  • Include or extend other templates for modular design

This makes it possible to build complex, data-driven web pages without mixing raw Python code directly into HTML.

Check out Create a Card with a Button in Django

Method 1: Pass Variables from Views to Templates

The most common way to output Python data to HTML is by passing context variables from your Django view to the template.

Step-by-step example:

Let’s say you are building a simple website for a local farmers’ market in California and want to display a list of fresh produce available today.

views.py

from django.shortcuts import render

def market_view(request):
    produce_list = ['Apples', 'Oranges', 'Kale', 'Tomatoes', 'Almonds']
    context = {
        'market_name': 'Sunnyvale Farmers Market',
        'produce': produce_list,
        'open_today': True,
    }
    return render(request, 'market.html', context)

market.html

<!DOCTYPE html>
<html>
<head>
    <title>{{ market_name }}</title>
</head>
<body>
    <h1>Welcome to {{ market_name }}</h1>

    {% if open_today %}
        <p>We are open today! Here is what’s fresh:</p>
        <ul>
            {% for item in produce %}
                <li>{{ item }}</li>
            {% endfor %}
        </ul>
    {% else %}
        <p>Sorry, we are closed today. Please come back tomorrow!</p>
    {% endif %}
</body>
</html>

When a user visits the page, Django renders the market.html template, replacing the placeholders with the Python data passed in the context dictionary. This approach is clean and simple, perfect for rendering dynamic content like lists, flags, or simple variables.

You can refer to the screenshot below to see the output.

django python html

Read Create a User Profile Using Django

Method 2: Use Template Filters and Tags for Data Formatting

Sometimes, you need to format or manipulate data directly in the template without changing your Python code.

Django provides built-in template filters and tags to help with this.

For example, suppose you want to display the current date in a friendly format on your page.

Example:

Modify your view to pass the current date.

from django.shortcuts import render
from datetime import datetime

def market_view(request):
    produce_list = ['Apples', 'Oranges', 'Kale', 'Tomatoes', 'Almonds']
    context = {
        'market_name': 'Sunnyvale Farmers Market',
        'produce': produce_list,
        'open_today': True,
        'today': datetime.now(),
    }
    return render(request, 'market.html', context)

Update your template to format the date:

<p>Today is {{ today|date:"F j, Y" }}</p>

This would output something like:

Today is August 5, 2025

You can also use filters like upper, lower, default, and many more to control the output without touching your Python code.

You can refer to the screenshot below to see the output.

python django html

Read Create a Search Autocomplete with a Filter in Django

Method 3: Create Custom Template Filters for Advanced Formatting

In some cases, the built-in filters aren’t enough. You might want to create your custom filter.

For example, let’s say you want to highlight produce names that are nuts (like “Almonds”) by making them bold.

How to create a custom filter:

  1. Create a new Python file inside your app directory called templatetags/custom_filters.py.
  2. Add the following code:
from django import template

register = template.Library()

@register.filter(name='highlight_nuts')
def highlight_nuts(value):
    nuts = ['Almonds', 'Walnuts', 'Pecans']
    if value in nuts:
        return f"<strong>{value}</strong>"
    return value
  1. In your template, load the custom filter and use it:
{% load custom_filters %}

<ul>
    {% for item in produce %}
        <li>{{ item|highlight_nuts|safe }}</li>
    {% endfor %}
</ul>

The |safe filter is necessary to allow HTML tags to be rendered instead of escaped.

This method gives you full control over how Python data is presented and formatted in your templates.

Check out Register User with OTP Verification in Django

Method 4: Use Django’s Class-Based Views with Context Data

If you prefer class-based views (CBVs), you can also pass context data easily.

Here’s how to do the same farmers market example with a CBV:

from django.views.generic import TemplateView
from datetime import datetime

class MarketView(TemplateView):
    template_name = 'market.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['market_name'] = 'Sunnyvale Farmers Market'
        context['produce'] = ['Apples', 'Oranges', 'Kale', 'Tomatoes', 'Almonds']
        context['open_today'] = True
        context['today'] = datetime.now()
        return context

This approach is great for more complex views where you want to organize logic cleanly.

Read Python Django Convert Date Time to String

Tips for Outputting Python to HTML in Django

  • Avoid putting raw Python code in templates. Use views and context to prepare data.
  • Escape user input by default. Django templates automatically escape variables to prevent XSS attacks.
  • Use template inheritance to keep your HTML DRY (Don’t Repeat Yourself).
  • Leverage Django’s built-in filters and tags before creating custom ones.
  • Test your templates with different data to ensure your output looks consistent.

Outputting Python data to HTML in Django is easy once you understand the flow from views to templates. Whether you’re building a simple site for a local farmers’ market in the USA or a complex data-driven dashboard, Django’s templating system gives you the flexibility and power to display your Python data cleanly and efficiently.

If you want to dive deeper, explore Django’s official documentation on templates or experiment with custom tags and filters. With practice, you’ll find this approach indispensable for building maintainable, dynamic web applications.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.