0 day streak
python / beginner
Snippet

Passing Data to Templates in Views

Views use a dictionary called 'context' to pass dynamic data from Python logic to HTML templates.

snippet.py
python
1
2
3
4
5
from django.shortcuts import render
def profile_view(request):
user_data = {'username': 'coder123'}
return render(request, 'profile.html', user_data)
django
Breakdown
1
def profile_view(request):
Defines a function-based view that receives a web request.
2
user_data = {'username': 'coder123'}
Creates a dictionary containing the data to be sent to the template.
3
return render(request, 'profile.html', user_data)
Combines the request, template, and data into a single web response.