django使用视图显示html,Django实践:在视图中使用模板

前面讲了这么多理论的东西,都快受不了了吧。那么这里先不讲模板的规则机制什么的,我们来动手写一个模板的例子,实践一下,有不懂再回去继续讲规则。

1. 定义你的 templates 目录

去 settings.py 这个文件,配置 templates 目录:

TEMPLATE_DIRS = (

# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".

# Always use forward slashes, even on Windows.

# Don't forget to use absolute paths, not relative paths.

'E:/PythonProject/templates',

)

2. 编写 template 文件 current_datetime.html

简明现代魔法 on Python Django

现在的时间是 {{ current_date }}.

简明现代魔法 on Python Django

3. 编写 views 层的 def

from django.template.loader import get_template

from django.template import Context

from django.http import HttpResponse

import datetime

def current_datetime_template(request):

now = datetime.datetime.now()

t = get_template('current_datetime.html')

html = t.render(Context({'current_date': now}))

return HttpResponse(html)

4. 设定 urls.py 的路径

from django.conf.urls.defaults import *

from PythonProject.views import hello, current_datetime, current_datetime_template, hours_ahead, loop_test

urlpatterns = patterns('',

('^hello/$', hello),

('^time/$', current_datetime),

('^time2/$', current_datetime_template),

(r'^time/plus/(\d{1,2})/$', hours_ahead),

('^test/$', loop_test),

)

OK,我们打开 http://127.0.0.1:8000/time2/,成功,页面显示:

现在的时间是 July 24, 2013, 2:34 p.m..

简明现代魔法 on Python Django

就这么简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值