English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django View Creation

View function, or abbreviated as "view", is a simple Python function that accepts a web request and returns a web response. This response can be the HTML content of a web page, or a redirect, or404error, or XML document, or image/pages, etc. For example: create a page using a view, please note that you need to associate a view with a URL and consider it as a web page.
In Django, views must be created in the application's views.py file.

Simple view

We will create a simple view in myapp to display: "welcome to w3codebox !"

View the following view −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.http import HttpResponse
 def hello(request):
    text = """<h1>welcome to w3codebox !/h1">"""
    return HttpResponse(text)

In this view, we use HttpResponse to present HTML (you may have noticed that we have hardcoded HTML in the view). In this view, we just need to map it to a page (this will be discussed in the upcoming chapter).

We use HttpResponse before rendering the view HTML. This is not the best way to render a webpage. Django supports the MVT pattern, which renders the view first before rendering the HTML. - MVT is what we need -

A template file: myapp/templates/hello.html

Now, the content of our view is as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.shortcuts import render
 def hello(request):
    return render(request, "myapp/template/hello.html", {})

Parameters that the view can accept -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.http import HttpResponse
 def hello(request, number):
    text = "<h1>welcome to my app number %s !</h1>"% number
    return HttpResponse(text)

When linked to a URL, the page will display the value passed as a parameter. Note that the parameter will be passed through the URL (to be discussed in the next chapter).