Django框架之再显示未来n小时的时间

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43862765/article/details/102474787

①先开始看截图吧:

第一个界面,就是我们的默认界面,显示“Hello World!”

下面是在127.0.0.1:8000后面写上/time,即将开启下一个页面:

紧接着,在后面接着写上plus/12,则会显示:

②代码对大佬来说很简单,但是对于我这样的小白来说,躺过了好多坑和bug才最终实现的:

代码如下:

urls.py

from django.conf.urls import include,url
from django.contrib import admin
from . import views
urlpatterns = [
    url(r'^admin/',admin.site.urls),
    url(r'^$',views.hello),
    url(r'^time/$',views.current_datetime),
    url(r'^time/plus/(\d{1,2})/$',views.hours_ahead),
    ]
#url使用正则表达式模式匹配浏览器中的URL,把它映射到Django项目中的某个模块上
#urlpatterns即url()实例列表,负责定义URL及处理URL代码之间的映射

views.py

from django.http import HttpResponse
import datetime
def hello(request):
    return HttpResponse("Hello world!")
def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
def hours_ahead(request,offset):
    try:
        offset = int(offset)
    except Exception as Error:
        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)

③在这里,我要强调一点:

1)就像我之前的那篇博客,为什么r'^time/$'不行,我觉得是我开始照书上敲的时候html的圆括号应该编程<>

2)/d{1,2}是正则表达式的用法,用来实现1位和2位数字的输入(之前了解过一些正则表达式)

3)请留下你们最可爱的""吧

猜你喜欢

转载自blog.csdn.net/weixin_43862765/article/details/102474787