博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django学习(五) 定义视图以及页面模板
阅读量:7064 次
发布时间:2019-06-28

本文共 1354 字,大约阅读时间需要 4 分钟。

  请求解析一般都是通过请求的request获取一定参数,然后根据参数做一定业务逻辑判断,这其中可能包括查询数据库,然后将需要返回的数据封装成一个HttpResponse返回。

  代码如下:

这是一个简单的处理请求的函数,对应之前url映射的  url(r'^articles/([0-9]{4})/$', views.year_archive),django会将url中用()包起来的内容作为变量传给函数,此处year_archive中的year变量就是([0-9]{4})代表的值。

Article.objects.filter(pub_date__year=year)过滤出发布日期是year的数据。注意pub_date__year,数据库表中只有pub_date字段,pub_date__year代表值取年。

所以可以认为这是django默认提供的一种接口查询方式。

然后将返回的list列表和year再组装成一个字典数据。

最后调用django提供的函数render返回。render完成的事情其实就是选择一个模板,创建一个Context对象,然后将这些数据放到创建的一个HttpResponse中去。

mysite/news/views.pyfrom django.shortcuts import renderfrom .models import Articledef year_archive(request, year):    a_list = Article.objects.filter(pub_date__year=year)    context = {
'year': year, 'article_list': a_list} return render(request, 'news/year_archive.html', context)

   上面的代码其实是对以下数据进行了封装,render中封装了以下代码的作用。

  

from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):    now = datetime.datetime.now()    # Simple way of using templates from the filesystem.    # This is BAD because it doesn't account for missing files!    fp = open('/home/djangouser/templates/mytemplate.html')    t = Template(fp.read())    fp.close()    html = t.render(Context({
'current_date': now})) return HttpResponse(html)

 

转载于:https://www.cnblogs.com/nihousheng/p/4539234.html

你可能感兴趣的文章
HtmlAttribute HTML属性处理类
查看>>
[书目20130316]jQuery UI开发指南
查看>>
Sql Server系列:开发存储过程
查看>>
Find INTCOL#=1001 in col_usage$?
查看>>
AutoCAD 命令统计魔幻球的实现过程--(3)
查看>>
dp学习笔记1
查看>>
newlisp debugger
查看>>
Java进阶02 异常处理
查看>>
java 动态代理
查看>>
微信5.0绑定银行卡教程
查看>>
数字转换为壹仟贰佰叁拾肆的Java方法
查看>>
一个表单对应多个提交按钮,每个提交按钮对应不同的行为
查看>>
tomcat集群时统计session与在线人数
查看>>
Android程序完全退出
查看>>
【Linux】目录权限与文件权限
查看>>
如何将阿拉伯数字每三位一逗号分隔,如:15000000转化为15,000,000
查看>>
select的使用(一)
查看>>
[leetcode]Search a 2D Matrix @ Python
查看>>
java.io.BufferedOutputStream 源码分析
查看>>
Load resources from classpath in Java--reference
查看>>