Django学习(五) 定义视图以及页面模板

  请求解析一般都是通过请求的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.py

from django.shortcuts import render

from .models import Article

def 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, Context
from django.http import HttpResponse
import datetime

def 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