0
0
Djangoframework~5 mins

Returning HTML templates in Django

Choose your learning style9 modes available
Introduction

Returning HTML templates lets your web app show nice pages to users. It connects your data with a design to make web pages.

When you want to show a homepage with text and images.
When you need to display a list of items from a database.
When you want to show a form for users to fill out.
When you want to create a user profile page with dynamic info.
When you want to build a blog post page with content from your app.
Syntax
Django
from django.shortcuts import render

def view_name(request):
    context = {'key': 'value'}  # data to send to template
    return render(request, 'template_name.html', context)

render is a Django shortcut that combines loading a template and returning an HTTP response.

The context is a dictionary with data you want to show in the template.

Examples
Returns a simple template without extra data.
Django
from django.shortcuts import render

def home(request):
    return render(request, 'home.html')
Sends user info to the template to show dynamic content.
Django
from django.shortcuts import render

def profile(request):
    user_info = {'name': 'Alice', 'age': 30}
    return render(request, 'profile.html', user_info)
Passes a list to the template to display multiple items.
Django
from django.shortcuts import render

def items_list(request):
    items = ['apple', 'banana', 'cherry']
    return render(request, 'items.html', {'items': items})
Sample Program

This view sends a name to the greeting.html template to show a personalized message.

Django
from django.shortcuts import render

def greeting(request):
    context = {'name': 'Friend'}
    return render(request, 'greeting.html', context)
OutputSuccess
Important Notes

Make sure your template files are in the correct folder (usually templates/ inside your app).

Context keys become variables you can use inside the HTML template with {{ key }} syntax.

Use Django's template language to add logic like loops and conditions inside your HTML.

Summary

Use render() to return HTML pages from views.

Pass data as a dictionary to show dynamic content in templates.

Templates and views work together to create user-friendly web pages.