目标:使用模板实现在页面上显示一个字符串
步骤:
1.通过PyCharm创建一个DJango项目,并在项目文件夹中的templates文件夹下创建一个python文件MyTemp1用于创建一个模板。模板内容如下:
<h1>{{ hello }}</h1>
2.创建模板视图文件TempView.py,即python文件。
from django.shortcuts import render def hello(request): context = {} context['hello'] = '生活如此美好!' return render(request, 'MyTemp1.html', context)
3.项目文件中找到urls.py文件夹,导入python视图文件并在urlpatterns=[]中进行配置。内容如下:
from django.contrib import admin from django.urls import path from django.conf.urls import url from MySecondProject import TempView as MyAppViews # 添加模板 urlpatterns = [ #使用模板 url(r'^$', MyAppViews.hello), path('admin/', admin.site.urls), ]
4.注意使用模板是需要在项目中的settings.py文件夹中进行设置,具体如下:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #'DIRS': [os.path.join(BASE_DIR, 'templates')] 'DIRS': [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', ], }, }, ]
5.运行结果如下:
本人刚接触django所以不是很深入,希望对看到的人有帮助。