Django视图函数
一、视图函数
1. 视图函数的第一个参数一定是一个HTTPRequest类型的对象,这个对象是Django自动创建的,具体形参名通常用request。通过这个对象,可以调用请求的一些参数,比如request.path,request.method,request.META去查看请求信息。
2. 视图函数必须返回一个HTTPResponse类型的对象。(也可以用JsonResponse,
StreamingHttpResponse,
)FileResponse类返回非http对象
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
实际使用中,通过加载视图模板的方式,将视图函数与前端显示层解耦。
from django.http import HttpResponse
from django.template import loader
from .models import Question def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
但是这么写,视图函数的语法比较繁琐,所以引入快捷方式,render()函数。
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
render()函数的第一个位置参数是请求对象,第二个位置参数是模板,还可以有一个可选的第三参数---一个字典,包含需要传递给模板的数据。最后render函数返回一个经过字典数据渲染过的模板封装而成的HttpResponse对象。
3. 对于视图函数中操作模型时,如果找不到模型的值会返回404错误。
from django.http import Http404
from django.shortcuts import render
from .models import Question
# ...
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
可以使用快捷方式,get_object_or_404()函数和get_list_or_404()函数(用来替代filter()函数,当查询列表为空时弹出404错误。)
from django.shortcuts import get_object_or_404, render
from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
将一个模型作为第一个位置参数,后面可以跟上任意个数的关键字参数(这些关键字参数是传递给模型管理器的get()函数的),如果对象不存在则弹出Http404错误。
4.HTTPResponse类有很多子类,可以返回不同状态的应答。
HttpResponseRedirect 302
HttpResponsePermanentRedirect 301
HttpResponseNotModified 304
HttpResponseBadRequest 400
HttpResponseNotFound 404
HttpResponseForbidden 403
HttpResponseNotAllowed 405
HttpResponseGone 410
HttpResponseServerError 500
例如返回404:
from django.http import HttpResponse, HttpResponseNotFound def my_view(request):
# ...
if foo:
return HttpResponseNotFound('<h1>Page not found</h1>')
else:
return HttpResponse('<h1>Page was found</h1>')
5.由于404错误的应用情景比较多,Django有一套默认处理机制。首先,当发生404异常时,会在根URLconf中查找处理404错误的handler404(并且只能在根URLconf中查找),如果找到了则按设置的错误视图模板显示404页面(还有处理500、403、400的handler)。
handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
如果没有设置handler404,会自动调用内置的django.views.defaults.page_not_found(),这个函数返回一个渲染“Lib\site-packages\django\contrib\admin\templates\admin\404.html”模板的HttpResponseNotFound对象。因此,通常情况下,可以不需要写404错误页面,在视图函数中抛出404异常时,框架会调用自带的404.html;如果需要自定义404页面,则可以在根URLconf中设置指向的自定义404页面,或者可以自编一个404.html文件放在模板树(template tree)的前面(一般是模板的根目录下),屏蔽默认404模板。如果settings里面的DEBUG设置为False,并且不创建404.html文件的话,会出现一个Http500错误,所以创建一个404.html模板文件是很有必要的。如果DEBUG设置为True,那么404view将不会被用到,因此404.html模板也不会被渲染,取而代之的将是浏览器上出现的traceback错误。在django的URLconf中无法匹配任何一个正则表达式时也会调用404页面。
Django视图函数的更多相关文章
- django视图函数及快捷方式
视图函数,简称视图,本质上是一个简单的Python函数,它接受Web请求并且返回Web响应. 响应的内容可以是HTML网页.重定向.404错误,XML文档或图像等任何东西.但是,无论视图本身是个什么处 ...
- django视图函数解析(三)
1 视图views概述 1 作用: 视图接受web请求并响应web请求 2 本质: 视图就是python中的处理函数 3 响应: 一般是一个网页的HTML内容.一个重定向.错误信息页面.json格式的 ...
- 【6】Django视图函数
治大国若烹小鲜.以道莅天下 --老子<道德经> 本节内容 Django web项目的运行流程分析 视图处理函数的定义 多视图处理函数及接收参数 1. web项目运行流程分析 通常情况下,完 ...
- Django视图函数之三种响应模式
视图函数响应处理: from django.shortcuts import render,HttpResponse,redirect (1)render 处理模板文件,可以渲染模板,第一个参数必须为 ...
- Django视图函数函数之视图装饰器
FBV模式装饰器: 普通函数的装饰器(语法糖@) views.py from django.shortcuts import render def wrapper(f): def inner(*arg ...
- Django视图函数之FBV与CBV模式
FBV模式: FBV(function base views) 就是在视图里使用函数处理请求. 一般直接用函数写的都属于是FBV模式. veiws.py from django.shortcuts i ...
- Django视图函数之request请求与response响应对象
官方文档: https://docs.djangoproject.com/en/1.11/ref/request-response/ 视图中的request请求对象: 当请求页面时,Django创建一 ...
- Django视图函数:CBV与FBV (ps:补充装饰器)
CBV 基于类的视图 FBV 基于函数的视图 CBV: 1 项目目录下: 2 urlpatterns = [ 3 path('login1/',views.Login.as_view()) #.as ...
- django视图函数中 应用装饰器
from django.shortcuts import render, redirect, HttpResponse from .forms import LoginForm, Registrati ...
随机推荐
- PAT 1017
1017. Queueing at Bank (25) Suppose a bank has K windows open for service. There is a yellow line in ...
- Distributed locks with Redis--官方
原文:http://redis.io/topics/distlock Distributed locks with Redis Distributed locks are a very useful ...
- Cannot open URL…
启动intellij时出现cannot open URl,原来是过滤器写错,把所有地址都拦截了..
- c/c++将整数转换为字符串
#include <iostream> using namespace std; int main(int argc, char **argv) { ; iint i,j; ],e[]; ...
- 关于JFace中的TableViewer和TreeViewer中的
TableViewer类 构造方法摘要: 方法摘要: 在做的这几个练习中,发现,getTable(),refresh(),remove(),setSelection()方法经常使用. TreeView ...
- uiatuomator如何调试
博主较笨,在使用junit 和uiatuomator结合时不知道怎么调试,因为uiatuomator一直是push在手机上,而junit是需要代码运行的,那我该怎么办,现在发一下不知道是哪位大神写的代 ...
- GridView不換行
在开发中用到了需要ScrollView嵌套GridView的情况,由于这两款控件都自带滚动条,当他们碰到一起的时候便会出问题,即GridView会显示不全. 解决办法,可以把ScrollVIew给删除 ...
- C# String 前面不足位数补零的方法 PadLeft
PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度PadLeft(int totalWid ...
- web app开发中 iPhone、iPad默认按钮样式问题
webapp开发过程中,用html5+css3很方便,而且可以很方便的编译到Android ios等不同平台,但是ios需要单独处理一下,不然会出现一些想象不到的问题.下面就介绍一下各种问题的解决方法 ...
- 提高查询速度:SQL Server数据库优化方案
查询速度慢的原因很多,常见如下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列导致查询不优化. 4.内存不足 ...