Django’s render() shortcut turns a view’s template and data into an HTTP response. A view does its logic, prepares context data, loads a named template, and returns the rendered HTML to the browser—without making you write the longer template-loading sequence yourself. section 3.6 section 3.10
Call render() with the incoming request and a template name. Pass a dictionary as the optional context argument when the template needs data; optional arguments can also set the response MIME type or HTTP status code. Django finds template files through the TEMPLATES configuration in settings.py. section 3.6 section 3.10
Render a news page
A news() view imports render, creates a data dictionary whose news key holds message strings, and returns render(request, "news.html", data). In news.html, a {% for %} loop reads news and renders each item as a list entry. Registering path('news/', home_views.news, name="news") makes that view reachable. section 3.6
Follow the request path from browser to page:
- A URL route selects the view function for /news/. section 3.6
- The view receives an HttpRequest, prepares its context dictionary, and calls render(). section 3.6
- render() loads news.html, combines its template code with context values, and returns an HttpResponse. section 3.6
- The template can use variables, loops, conditionals, tags, and filters to control the resulting HTML. section 3.10 section 3.5.6
Listing 3.5 Adding a view for the news page
# RiffMates/home/views.py
from django.shortcuts import render
...
def news(request):
data = {
'news':[
"RiffMates now has a news page!",
"RiffMates has its first web page",
],
}
return render(request, "news.html", data)
The complete view shows the usual compact pattern: import render, assemble context, and return the shortcut call. section 3.6
Listing 3.9 HTML template to be rendered by the news view
<!-- RiffMates/templates/news.html -->
<!doctype html>
<html lang="en">
<head>
<title>RiffMates News</title>
</head>
<body>
<h1>RiffMates News</h1>
<ul>
{% for item in news %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
The matching template demonstrates how the context’s news list becomes HTML through a template for-loop. section 3.6
