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