人生苦短 ~ html
Tips:仅适用于 Python 3+(反正差异不大,py2 改改也能用)。由于据 Python 之父 Guido van Rossum 说会在 2020 年中止对 Python 2 的官方支持,因此若是你还在使用 Python 2 那就要早作准备了,毕竟没有官方的支持使用起来也不顺心的。python
1. 建立模版目录sql
在咱们的项目 HelloDjango 目录下建立文件夹 templatesdjango
HelloDjango |----HelloDjango |----manage.py |----db.sqlite3 |----mydjango |----templates |----index.html
2. 设置模版路径函数
打开咱们的项目 HelloDjango 目录的文件夹 HelloDjango,找到并打开文件 settings.py,找到 TEMPLATES 中 DIRS,修改以下红色内容:学习
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', ], }, }, ]
3. 添加模版ui
在咱们建立的 templates 目录下面建立咱们的模板 index.html 文件,文件内容以下:spa
<!DOCTYPE html> <html> <head> <title>HelloDjango</title> </head> <body> <a href="/mydjango/index/">Index</a><hr /> <h3>HelloDjango</h3> 动态数据:<strong>{{ mydata }}</strong> </body> </html>
4. 修改视图函数debug
打开应用中 /mydjango/views.py 文件,修改学习笔记一中的 hello 视图函数,修改后以下:code
def hello(request): data = { 'mydata':'哇~ This is Return MSG' } return render(request, 'index.html', data)
其中 mydata 和 html 模版中的 {{mydata}}相互对应,是须要回显的数据
5. 结果
打开服务 python manage.py runserver,输入网址 http://127.0.0.1:8000/mydjango/hello/ 访问:
~ 我学 Python