Django Template Rendering Examples

Discover practical examples of Django template rendering to enhance your web development projects.
By Taylor

Understanding Django Template Rendering

Django is a powerful web framework that allows developers to create dynamic web applications with ease. One of its key features is the template rendering system, which separates the presentation layer from the business logic. This means you can define how your data is displayed in a clean and organized manner without mixing it with your Python code. In this post, we’ll explore three diverse examples of Django template rendering that demonstrate its versatility and ease of use.

Example 1: Rendering a List of Items

Use Case

Imagine you are building an online store and you want to display a list of products on your homepage. This example shows how to render a list of products using a Django template.

# views.py
from django.shortcuts import render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'product_list.html', {'products': products})
<!-- product_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product List</title>
</head>
<body>
    <h1>Available Products</h1>
    <ul>
        {% for product in products %}
            <li>{{ product.name }} - ${{ product.price }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Notes

  • The Product model is assumed to have name and price fields.
  • You can customize the HTML structure to include images or descriptions.

Example 2: Conditional Rendering Based on User Authentication

Use Case

In an application where users can log in, you may want to display different content based on whether a user is authenticated or not. This example illustrates how to use template tags to conditionally render content.

# views.py
from django.shortcuts import render

def home(request):
    return render(request, 'home.html')
<!-- home.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h1>Welcome to Our Website</h1>
    {% if user.is_authenticated %}
        <p>Hello, {{ user.username }}! You are logged in.</p>
    {% else %}
        <p>Please <a href="/login/">log in</a> to access more features.</p>
    {% endif %}
</body>
</html>

Notes

  • The user context variable is automatically available in templates when using Django’s authentication system.
  • You can expand this example by including links to log out or register.

Example 3: Rendering a Form with Error Handling

Use Case

When creating a form for user input, you want to handle and display any validation errors to improve user experience. This example demonstrates how to render a form and show validation errors in the template.

# views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form data here
            return HttpResponseRedirect('/success/')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})
<!-- contact.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
    {% if form.errors %}
        <div class="error">
            <p>Please fix the following errors:</p>
            <ul>
                {% for field in form %}
                    {% for error in field.errors %}
                        <li>{{ field.label }}: {{ error }}</li>
                    {% endfor %}
                {% endfor %}
            </ul>
        </div>
    {% endif %}
</body>
</html>

Notes

  • The ContactForm is assumed to be a Django form class defined in forms.py.
  • The {% csrf_token %} tag is necessary for security when submitting forms.

These examples of Django template rendering illustrate how to effectively display dynamic content, handle user authentication, and manage form submissions in a user-friendly way. With these techniques, you can create more interactive and responsive web applications.