Django follows MVT (Model View Template) pattern. It is slightly different from MVC.
Model: It is the data access layer. It contains everything about the data, i.e., how to access it, how to validate it, its behaviors and the relationships between the data.
Let’s see an example. We are creating a model Employee who has two fields first_name and last_name.
from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
View: It is the business logic layer. This layer contains the logic that accesses the model and defers to the appropriate template. It is like a bridge between the model and the template.
import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
now = datetime.datetime.now()
html = ”
Now time is %s.
” % now
return HttpResponse(html) # rendering the template in HttpResponse
Template: It is a presentation layer. This layer contains presentation-related decisions, i.e., how something should be displayed on a Web page or other type of document.
To configure the template system, we have to provide some entries in settings.py file.
TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR,’templates’)],
‘APP_DIRS’: True,
‘OPTIONS’: {
‘context_processors’: [
‘django.template.context_processors.debug’,
‘django.template.context_processors.request’,
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.messages’,
],
},
},
]