Django View Creation

0
196

A view is a function supported by Python which accepts a web request and returns a web response. This web response can consist of any of the following:

Also Read: Django Application Life Cycle

* HTML content included in a web page.
* redirected web page
* not found error (i.e., 404 error)
* an XML document
* an image

and a few others.

In other words, you create a view that can be linked to a web page. To do so, you are required to link your view to the desired URL.

Django lets you create a view for an application by the use of views.py file.

Creation of a Simple View
Here, we will be creating the simplest of the view in your already created myapp application. The view will only display “Welcome to MyApp”.

The coding for this simple view creation is provided below:

from django.http import HttpResponse
def hello(request):
   text = “””<h1>welcome to my app !</h1>”””
   return HttpResponse(text)

In the above coding, we have included HttpResponse to provide the HTML code. As we are required to display the response as a web page only, that is why we need to map it to a URL.

Well, the above code is not the best way by which we can render HTML in an application’s view. The MVT pattern of Django makes it much easier. After the use of Django – MVT, we need to make use of a template, which is

Myapp/templates/hello.html

After the required changes, the new view will appear like the following:

from django.shortcuts import render
def hello(request):
   return render(request, “myapp/template/hello.html”, {})

Passing Parameters to A View
It is possible for a view to have parameters which imply that a view accepts parameters. Whenever this view gets linked to a URL, it will display the number which is passed in it as the parameter.

from django.http import HttpResponse
def hello(request, number):
   text = “<h1>welcome to my app number %s!</h1>”% number
   return HttpResponse(text)