Django 遵循 MVT(模型视图模板)模式。 它与 MVC 略有不同。
模型:它是数据访问层。 它包含有关数据的所有内容,即如何访问它、如何验证它、它的行为以及数据之间的关系。
让我们看一个例子。首先创建一个模型 Employee,它有两个字段 first_name
和 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)
视图 :是业务逻辑层。 该层包含访问模型并遵循适当模板的逻辑。 它就像模型和模板之间的桥梁。
import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
now = datetime.datetime.now()
html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
return HttpResponse(html) # rendering the template in HttpResponse
模板 :它是一个表示层。 该层包含与表示相关的决策,即,应如何在网页或其他类型的文档上显示某些内容。要配置模板系统,必须在 settings.py
文件中提供一些条目。
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',
],
},
},
]