Python Web框架Django模板入门

创建目录HelloWorld/templates并建立appblog.html文件

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>{{ hello }}</h1>
</body>
</html>

修改文件HelloWorld/HelloWorld/settings.py,修改TEMPLATES中的DIRS[BASE_DIR+"/templates",]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
...

修改文件HelloWorld/HelloWorld/views.py,增加一个新的对象,用于向模板提交数据:

1
2
3
4
5
6
from django.shortcuts import render

def appblog(request):
context = {}
context['hello'] = 'http://www.appblog.cn'
return render(request, 'test.html', context)

配置路由HelloWorld/HelloWorld/urls.py

1
2
3
4
5
6
from django.urls import path
from . import views

urlpatterns = [
path('appblog/', views.appblog),
]

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :