All technological notes.
HttpResponse ObjectsHttpResponse objects are applications’ responsibility.HttpResponse.HttpResponse ClassInstantiates an HttpResponse object with the given page content, content type, and headers.
Syntax:
HttpResponse(content=b'', content_type=None, status=200, reason=None, charset=None, headers=None)
content:
content_type:
MIME type to fill the HTTP Content-Type header.'text/html; charset=utf-8'status:
reason:
charset:
headers:
HttpResponse subclassesHttpResponse subclasses that handle different types of HTTP responses.django.http.| Subclass | Description | Status code |
|---|---|---|
HttpResponseRedirect() |
redirect to a target url | 302 |
HttpResponsePermanentRedirect() |
returns a permanent redirect | 301 |
HttpResponseNotModified() |
a page hasn’t been modified since last request | 304 |
HttpResponseBadRequest() |
400 status code. | 400 |
HttpResponseNotFound() |
404 status code. | 404 |
HttpResponseForbidden() |
403 status code. | 403 |
HttpResponseNotAllowed() |
405 status code. | 405 |
HttpResponseGone() |
410 status code. | 410 |
HttpResponseServerError() |
500 status code. | 500 |
JsonResponse ObjectsHttpResponse subclass that helps to create a JSON-encoded response.Its default Content-Type header is set to application/json.
JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
Parameter:
data:
encoder:
django.core.serializers.json.DjangoJSONEncodersafe
TrueTrue and a non-dict object is passed as the first argument, a TypeError will be raised.False, any object can be passed for serialization (otherwise only dict instances are allowed).json_dumps_params
Example:
from django.http import JsonResponse
response = JsonResponse({"foo": "bar"}) # a dict object
response = JsonResponse([1, 2, 3], safe=False) # a non-dict object
StreamingHttpResponse Objectsused to stream a response from Django to the browser.
An example usage of StreamingHttpResponse under WSGI is streaming content when generating the response would take too long or uses too much memory.
FileResponse objectsFileResponse is a subclass of StreamingHttpResponse optimized for binary files.It uses wsgi.file_wrapper if provided by the wsgi server, otherwise it streams the file out in small chunks.
FileResponse(open_file, as_attachment=False, filename='', **kwargs)
open_file:
as_attachment: boolean
as_attachment=True, the Content-Disposition header is set to attachment, which asks the browser to offer the file to the user as a download. Otherwise, a Content-Disposition header with a value of inline (the browser default) will be set only if a filename is available.from django.http import FileResponse
response = FileResponse(open("myfile.png", "rb"))
django.shortcuts Moduledjango.shortcuts Module
render()Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
Syntax:
render(request, template_name, context=None, content_type=None, status=None, using=None)¶
Parameter:
request: Required.
template_name: Required.
context: Optional.
content_type: Optional.
'text/html'.status: Optional.
using: Optional
NAME of a template engine to use for loading the template.Example:
from django.shortcuts import render
def my_view(request):
# View code here...
return render(
request,
"myapp/index.html",
{
"foo": "bar",
},
content_type="application/xhtml+xml",
)
redirect()Returns an HttpResponseRedirect to the appropriate URL for the arguments passed.
Syntax:
redirect(to, *args, permanent=False, **kwargs)
Parameter can be:
get_absolute_url() function will be called.reverse() will be used to reverse-resolve the name.By default issues a temporary redirect; pass permanent=True to issue a permanent redirect.
Examples:
from django.shortcuts import redirect
# By passing some object; that object’s get_absolute_url() method will be called to figure out the redirect URL
def my_view(request):
obj = MyModel.objects.get(...)
return redirect(obj)
# By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method:
def my_view(request):
return redirect("some-view-name", foo="bar")
# By passing a hardcoded URL to redirect to
def my_view(request):
return redirect("/some/url/")
get_object_or_404()Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
Syntax:
get_object_or_404(klass, *args, **kwargs)
Parameter:
klass:
*args:
Q objects.**kwargs
get() and filter().Exmaple:
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
# equivalent to
def my_view(request):
try:
obj = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
get_list_or_404()Returns the result of filter() on a given model manager cast to a list, raising Http404 if the resulting list is empty.
Syntax:
get_list_or_404(klass, *args, **kwargs)
Parameter:
klass:
*args:
Q objects.**kwargs
get() and filter().Example:
from django.shortcuts import get_list_or_404
def my_view(request):
my_objects = get_list_or_404(MyModel, published=True)
# equivalent to
def my_view(request):
my_objects = list(MyModel.objects.filter(published=True))
if not my_objects:
raise Http404("No MyModel matches the given query.")