1.render(), redirect(), HttpResponse, JsonResponse
render(request, template, context) builds an HttpResponse from a template; redirect(to) builds a 302 to a URL, view name, or model; HttpResponse(content) wraps raw content directly; JsonResponse(data) serializes a dict to JSON with the right content type.
Key features
- render(request, template_name, context) is render_to_string() + HttpResponse() in one call
- redirect(to) accepts a URL string, a view name (resolved via reverse()), or a model instance (via get_absolute_url())
- JsonResponse defaults safe=True, which only accepts a dict — pass safe=False to serialize a list or other JSON-serializable object
- HttpResponse accepts str, bytes, or nothing (then use response.write()) — content_type defaults to "text/html"
- redirect() defaults to a 302 (temporary) — pass permanent=True for a 301
Response helpers at a glance
- render(): same page, HTML — template → HttpResponse
- HttpResponse(): same page, between HTML and data — raw content, any content_type
- redirect(): somewhere else / raw data, HTML — 302 to a URL, view name, or model
- JsonResponse(): somewhere else / raw data, data — dict → JSON, safe=False for a list
Command
from django.shortcuts import redirect
redirect("articles:detail", pk=5) # by view name
redirect("/articles/5/") # by literal URL
redirect(article_instance) # by model, via get_absolute_url()render() builds a template response, redirect() builds a 302 (to a URL, view name, or model), JsonResponse defaults to dict-only unless given safe=False.