Home >>Django Tutorial >Django Views

Django Views

Django Views

A view is basically the place where we put the business logic of the application. The view is the python function which takes the web request and returns a web response to the user. This response returned to the user can be the HTML contents of a Web page, or a redirect, or a 404 error.

For a Django app, all the view functions are created in the views.py file.

Simple Django View

//views.py


from django.http import HttpResponse  
def index(request):  
html = "<html><body><h3>Hello World.</h3></body></html>"  
return HttpResponse(html)
 

In the above code, first, we define a view function index that takes HTTP request and respond back. In this view, we use the HttpResponse to render HTML because we have the the HTML code in the view. View calls when gets mapped with URL in urls.py. For example

path('index/', views.index),

Django supports the MVT pattern so to make the precedent view we will need a template like “myapp/templates/hello.html”.

And now our view will look like −


from django.shortcuts import render

def hello(request):
   return render(request, "myapp/template/hello.html", {})