A view is a place where we put our business logic of the application. The view is a python function which is used to perform some business logic and return a response to the user. This response can be the HTML contents of a Web page, or a redirect, or a 404 error.
All the view function are created inside the views.py file of the Django app.
Django View Simple Example
Let's step through the code.
First, we will import DateTime library that provides a method to get current date and time and HttpResponse class.
Next, we define a view function index that takes HTTP request and respond back.
View calls when gets mapped with URL in urls.py. For example
Django provides various built-in error classes that are the subclass of HttpResponse and use to show error message as HTTP response. Some classes are listed below.
Django View Example
Django View HTTP Decorators
HTTP Decorators are used to restrict access to view based on the request method.
These decorators are listed in django.views.decorators.http and return a django.http.HttpResponseNotAllowed if the conditions are not met.
Django Http Decorator Example
This method will execute only if the request is an HTTP GET request.