目标:使用模板实现在页面上显示一个字符串
步骤:
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所以不是很深入,希望对看到的人有帮助。
这篇博客介绍了如何在Django项目中使用模板显示字符串。首先,通过PyCharm创建Django项目,并在templates文件夹下创建模板文件MyTemp1。接着,创建视图文件TempView.py,然后在urls.py中配置视图。最后,在settings.py中设置模板路径。运行项目后,成功在页面上展示了字符串。
1793

被折叠的 条评论
为什么被折叠?



