Django Views

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

//views.py

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

Output:

django views

Returning Errors

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.

ClassDescription
class HttpResponseNotModifiedIt is used to designate that a page hasn't been modified since the user's last request (status code 304).
class HttpResponseBadRequestIt acts just like HttpResponse but uses a 400 status code.
class HttpResponseNotFoundIt acts just like HttpResponse but uses a 404 status code.
class HttpResponseNotAllowedIt acts just like HttpResponse but uses a 410 status code.
HttpResponseServerErrorIt acts just like HttpResponse but uses a 500 status code.

Django View Example

// views.py

Output:

django views 1

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.

Syntax

require_http_methods(request_method_list)

Django Http Decorator Example

//views.py

This method will execute only if the request is an HTTP GET request.

//urls.py

Output:

django views 2
Next TopicTemplate




Latest Courses