Friday, 31 March 2017

django usage of template and view

django usage of template and view
django templates & views

In the last blog post we have seen how to write models for project. In this blog post we are going learn about usage of templates in django views.

Before start writing the view read the django request life cycle for better understanding.

Url dispatcher passes the request to the view. View is responsible for the processing of the request. As we know django follows the MVT architecture.

M -  model
V  -  view
T  -  template

  1. Model's allow us to connect with the databases for information.
  2. View takes the advantage of django models to get the information from the database[using queries] and processes it. We write business logic in views.
    We process the data in views and passes it to the template for showing processed data to the user.
  3. Template takes the processed data from the view and represent the data in a required formats like html, xml, json, etc.

We have discussed the theory part. Let's start the coding.
from django.conf.urls import url, include

urlpatterns = [
    url(r'^', include('library.urls')),
This is the root urls file of our application. 'include' will add the app(library) urls. Based on the regular expression pattern users request will be served.

from django.conf.urls import url
from library import views

urlpatterns = [
    url(r'^$', views.home, name="home"),
from django.shortcuts import render

def home(request):
    return render(request, 'home.html', {'say_hello': 'Hello World'})
<!DOCTYPE html>
    <html> <head>
        <title> Library Management </title> </head>
        <h1> {{ say_hello }}</h1>
We have imported 'views' module from the library app and mapped it to url. Whenever we request the url http://localhost:8000 in the browser it will the passed to the function home.
If we observe library/ we have imported the render from the django shortcuts module. render takes request, template name(path from template directories) and context data(the dictionary) and renders the template with context data and returns the http response. Browser receives the response and displays it to the user.
{{ say_hello }}  replaces with Hello World. Context is a dictionary with keys and values. say_hello is a key in the context so it will replaced by it's value.
It's just like string formatting in python.