【第三集】Django实现简单的动态页面内容

目录

一、计算当前日期和时间

1、VIEW

2、URL

二、显示当前时间和加上时间偏差量的时间(使用正则表达式)

1、VIEW

2、URL

3、运行调试


一、计算当前日期和时间

1、VIEW

from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

2、URL

from django.contrib import admin
from django.urls import path
from mysite.views import hello, current_datetime
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello),
path('time/', current_datetime)
]

二、显示当前时间和加上时间偏差量的时间(使用正则表达式)

1、VIEW

from django.http import Http404, HttpResponse
import datetime
def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
return HttpResponse(html)

2、URL

(1)一个URL模式就是一个正则表达式。因此,这里可以使用\d+来匹配1个以上的数字

(2)让我们把它限制在最大允许99个小时, 这样我们就只 允许一个或两个数字,正则表达式的语法就是 \d{1,2}

(3)用圆括号把 \d{1,2} 包围起来,正则表达式也是用圆括号来从文本里提取数据的(这里的文本数据是从浏览器地址栏里传过来的)

from django.contrib import admin
from django.urls import path, re_path
from mysite.views import hello, current_datetime, hours_ahead
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello),
path('time/', current_datetime),
re_path('time/plus/(\d{1,2})/', hours_ahead),
]

3、运行调试

(1)在完成视图函数和URL配置编写后,启动Django开发服务器,用浏览器访问 http://127.0.0.1:8000/time/plus/3/ 来确认它工作正常

(2)访问 http://127.0.0.1:8000/time/plus/100/ 来检验URL配置里设置的模 式是否只接受一个或两个数字。Django会显示一个和以前看到的 404 错误一 样的Page not found error 页面

(3)注释掉 hours_ahead 视图中的 offset = int(offset) 一行。你会看到一个包含大量信息的出错页 ,最上面 的一条 TypeError 信息是: “unsupported type for timedelta hours component: str” 。

Django 漂亮的出错页面:https://blog.csdn.net/bug4pie/article/details/80394945

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值