工作中Django总结之二(模板)

来源:互联网 发布:我想开发个软件 编辑:程序博客网 时间:2024/05/06 09:27

模板应用实例(MVC)

在项目project根目录下创建templates目录并建hello.html文件,目录结构为:

project|--project(文件夹)|--templates(文件夹)|--manage.py(文件)

project/templates/hello.html文件代码如下:

<h1>{{ hello }}</h1>这里的hello是占位符,需与view.py文件中的配置一致。

project/project/settings.py文件中的代码如下:

修改位置:...TEMPLATES = [    ......    'DIRS':[BASE_DIR+"/templates",],    ......]

project/project/view.py 文件修改如下:

# _*_ coding:utf-8 _*_#from django.http import HttpResponsefrom django.shortcuts import renderdef hello(request):    context          = {}    context['hello'] = 'Hello World!'    return render(request, 'hello.html', context) 使用render来代替之前使用的HttpResponse.render还使用了一个字典context作为参数。 context字典中元素的键值'hello'对应了模板中的变量"{{hello}}"    

project/project/urls.py中的代码修改如下:

from django.conf.urls import urlfrom . import viewurlpatterns = [    url(r'^hello$', view.hello),]

访问app的地址就可查看效果:127.0.0.1:8080/hello

0 0