django--02 模板的使用

参考链接:https://www.w3cschool.cn/django/django-template.html

1、新建模板目录  templates

2、在setting文件中注册模板

修改 TEMPLATES 中的 DIRS 为 [BASE_DIR+"/templates",]

 3、我们现在修改 view.py,增加一个新的对象,用于向模板提交数据

# -*- coding: utf-8 -*-

#from django.http import HttpResponse
from django.shortcuts import render

def hello(request):
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, 'hello.html', context)

可以看到,我们这里使用render来替代之前使用的HttpResponse。render还使用了一个字典context作为参数。

context 字典中元素的键值 "hello" 对应了模板中的变量 "{{ hello }}"。

 4、刷新界面:

原文地址:https://www.cnblogs.com/xbkp/p/7822110.html