Creating View in Django

Creating View in Django   

Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more.

Class Based View and Function based

Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can.

CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal

View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc.

Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page.

Simple View

We will create a simple view in myapplication to say “Welocome to django application”

See the following view –

from django.http import HttpResponse
 def hello(request):
    text = """<h1>Welcome to django  application</h1>"""
    return HttpResponse(text) 

In this view, we're using HTML response to render the HTML (as you've probably noticed we've hard-coded the HTML in the view). To view this view as a website, we simply need to map it to a URL (this will be discussed in a chapter to come).

We used the HTML response in the view before to render the HTML. This is not the most acceptable way to make papers. Django supports the MVT model so we'll need to render the previous view, Django-like MVT-

A template: myapplication/templates/hello.html

Code will look like a

from django.shortcuts import render
 def hello(request):
  return render(request, "myapplication/template/hello.html", {}) 

View can also be

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