Morden web application are all designed with MVC( Model, View, Controller ) pattern. But in django, the pattern name is MTV( Model, Template, View Function ). So in django, template html is the view, and view function plays the role of controller. This article will tell you how to create template and view function in django application with example, and how to return template html file as response in django view function. If you want to learn the complete process about how to create a website with django you can read How To Make A Website With Python And Django.
Django view function is defined in Django app views.py file. This function will accept a django.http.HttpRequest
object as the first parameter, it can also accept other parameters which are passed from the request url ( you can read article How To Pass Multiple Parameters Via Url In Django ). At the end of the view function, it will return a django.http.HttpResponse
object either created by HttpResponse class or render() shortcut with a html template file like below.
1. Return HttpResponse Object Created By django.http.HttpResponse Class.
from django.http import HttpResponse def index_page(request): # create a HttpResponse object and return it. response = HttpResponse('Hello World', content_type="text/plain") return response
2. Return HttpResponse Object Created By render Shortcut.
Please note the home_page.html template file should be saved in django_project_name(DjangoHelloWorld) / templates / django_app_name(dept_emp) folder.
def home_page(request): # invoke render shortcut to create HttpResponse object with template html file. resp = render(request, 'dept_emp/home_page.html') # set reponse headers and values. resp['Cache-Control'] = 'public,max-age=100000' resp['Vary'] = 'Accept-Encoding' return resp def dept_list(request): ...... # the render shortcut can accept a dictionary object that is saved in context. Then you can read those context data in template html files. return render(request, 'dept_emp/dept_list.html', {'dept_list': dept_list, 'paginator': paginator, 'base_url': base_url})
3. Return HttpResponse Object Created By django.http.HttpResponseRedirect Class.
def login_account(request): # the HttpResponseRedirect class return a HttpResponse object also, and the response is a redirect response which will change the web browser url. response = HttpResponseRedirect('/user/login_success/') # set cookie to transfer user name to login success page. response.set_cookie('user_name', user_name, 3600) return response