1.简单应用
首先,创建项目views_study,再创建子项目views_app
在主路由(即views_study下的urls.py)配置路由:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
# 请求到达主路由中会继续访问子路由
path("views_app/",include("views_app.urls"))
]
在子路由(即views_app的urls.py)下配置路由:
from django.urls import path
from . import views
urlpatterns=[
# 此为在视图中用函数执行请求
path("fbv/",views.fbv_func),
# 此为在视图中用类执行请求
path("cbv/",views.cbv_Views.as_view())
]
FBV(function base views)--->在视图里使用函数处理请求
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
# 需要传入request参数
def fbv_func(request):
# 用HttpResponse返回响应
return HttpResponse("这是在视图中用函数处理请求")
CBV(class base views)--->在视图里使用类处理请求
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.views import View
class cbv_Views(View):
def get(self,request):
return HttpResponse("这是在类中处理get请求")
def post(self,request):
return HttpResponse("这是在类中处理post请求")
2.返回错误响应
首先配置错误路由:
from django.urls import path
from . import views
urlpatterns=[
path("fbv/",views.fbv_func),
path("cbv/",views.cbv_Views.as_view()),
# 错误路由配置
path("error/<int:error_id>",views.error_test)
]
三种返回错误响应的方法:
1.以HttpResponseNotFound返回
2.以HttpResponse返回,括号内必须传入状态码status=...
3.以raise形式抛出Http404
HttpResponse,HttpResponseNotFound,Http404使用时都需要从django.http.response导入
from django.shortcuts import render
from django.http.response import HttpResponse,HttpResponseNotFound,Http404
# Create your views here.
def error_test(request,error_id):
if error_id>30:
return HttpResponseNotFound(f"HttpResponseNotFound error_id:{error_id}")
elif error_id>20:
return HttpResponse(f"HttpResponse error_id:{error_id}",status=404)
elif error_id>10:
raise Http404(f"Http404 error_id:{error_id}")
3.视图装饰器
@require_http_methods:要求视图只接收指定的http方法
@require_GET():仅仅允许GET方法
@require_POST():仅仅允许POST方法.
@require_safe():仅仅允许GET和HEAD方法
from django.shortcuts import render
from django.views import View
from django.views.decorators.http import require_http_methods,require_GET,require_POST,require_safe
# @require_http_methods(["GET","POST"])
# @require_GET
# @require_POST
# @require_safe
def decorator_test(request):
return HttpResponse("这是一个Get请求")
@login_required:必须登录才能访问装饰的视图函数,
用户未登录,则重定向到settings.LOGIN_URL(可手动配置):
LOGIN_URL="/views_app/nologin"
除非指定了login_url参数,例如:@login_required(login_url='/polls/login/')
该装饰器使用前需要from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.views import View
from django.contrib.auth.decorators import login_required
@login_required
def login_test(request):
return HttpResponse("用户已登录")
def nologin_test(request):
return HttpResponse("用户登陆失败")
4、请求和响应
1.HttpRequest
每一个用户请求在到达视图函数的同时,django会自动创建一个HttpRequest对象并把这个对象当做第一个参数传给要调用的views方法。HttpRequest对象里封装了本次请求所涉及的用户浏览器端数据、服务器端数据等,在views里可以通过request对象来调用相应的属性。
所有视图函数的第一个参数都是HttpRequest实例
属性(除非另有说明,否则所有属性均应视为只读):
-
HttpRequest.scheme:
表示请求使用的协议(http或https)
-
HttpRequest.body:
原始HTTP请求主体,类型是字节串。处理数据一些非html表单的数据类型很有用,譬如:二进制图像,XML等;
-
取form表单数据,请使用 HttpRequest.POST
-
取url中的参数,用HttpRequest.GET
-
-
HttpRequest.path:
表示请求页面的完整路径的字符串,不包括scheme和域名。
例: "/music/bands/the_beatles/"
-
HttpRequest.path_info:
在某些Web服务器配置下,主机名后的URL部分被分成脚本前缀部分和路径信息部分。path_info无论使用什么Web服务器,该属性始终包含路径的路径信息部分。使用此代替path可以使代码更容易在测试和部署服务器之间移动。
例如,如果WSGIScriptAlias你的应用程序设置为 "/minfo",则path可能是"/minfo/music/bands/the_beatles/" , path_info 会是 "/music/bands/the_beatles/"。
-
HttpRequest.method:
表示请求中使用的HTTP方法的字符串,是大写的。例如:
if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else()
-
HttpRequest.encoding:
表示当前编码的字符串,用于解码表单提交数据(或者None,表示使用该DEFAULT_CHARSET设置)。
可以设置此属性来更改访问表单数据时使用的编码,修改后,后续的属性访问(例如读取GET或POST)将使用新encoding值。
-
HttpRequest.content_type:
表示请求的MIME类型的字符串,从CONTENT_TYPE解析 。
-
HttpRequest.content_params:
包含在CONTENT_TYPE 标题中的键/值参数字典。
-
HttpRequest.GET:
包含所有给定的HTTP GET参数的类似字典的对象。请参阅QueryDict下面的文档。
-
HttpRequest.POST:
包含所有给定HTTP POST参数的类似字典的对象,前提是请求包含表单数据。请参阅QueryDict文档。POST不包含文件信息,文件信息请见FILES。
-
HttpRequest.COOKIES:
包含所有Cookie的字典,键和值是字符串。
-
HttpRequest.FILES:
包含所有上传文件的类似字典的对象
-
HttpRequest.META:
包含所有可用HTTP meta的字典
中间件设置的属性:
Django的contrib应用程序中包含的一些中间件在请求中设置了属性。如果在请求中看不到该属性,请确保使用了相应的中间件类MIDDLEWARE。
-
HttpRequest.session:
来自SessionMiddleware:代表当前会话的可读写字典对象。
-
HttpRequest.site:
来自CurrentSiteMiddleware: 代表当前网站的实例Site或 RequestSite返回get_current_site()
-
HttpRequest.user:
来自AuthenticationMiddleware:AUTH_USER_MODEL代表当前登录用户的实例
2.QueryDict
在一个 HttpRequest对象中,GET和 POST属性是django.http.QueryDict实例,该对象定义为相同的键的多个值的字典状类,继承自MultiValueDict, 而MultiValueDict则继承自dict
例如:网页URL:http://127.0.0.1:8000/views_app/querydict/?a=1&b=2&a=3
可知传入参数a和参数b
使用values.get(''a")和values["a"]时,后一个a会覆盖前一个a的值,但是使用values.getlist("a")方法则不会,list(values.item())用于返回所有的参数和值
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
def querydict(request):
values=request.GET
print("values-----",values)
print("a:",values['a'])
print("b:",values.get('b'))
print("list:",values.getlist('a'))
print("items:",list(values.items()))
return HttpResponse()
运行结果:
values----- <QueryDict: {'a': ['1', '3'], 'b': ['2']}>
a: 3
b: 2
list: ['1', '3']
items: [('a', '3'), ('b', '2')]
3.HttpResponse
返回给浏览器端的响应对象
属性:
-
HttpResponse.content:
表示响应的字符串
-
HttpResponse.charset:
表示响应将被编码的字符集,如果在HttpResponse实例化时没有给出,则会从中提取 content_type,如果没有设置content_type,则使用settings.DEFAULT_CHARSET
-
HttpResponse.status_code:
该响应的 HTTP 状态码
-
HttpResponse.reason_phrase:
响应的HTTP原因描述语,使用HTTP标准的默认原因描述语 除非明确设置,否则reason_phrase由 status_code 决定。
-
HttpResponse.streaming:
总是False,中间件通过此属性可以区分流式响应与常规响应
-
HttpResponse.closed:
如果response已经结束,则返回True,否则返回False
4.JsonResponse
包含json格式内容的响应
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views import View
def json_test(requst):
json_values={
"name":"xialei",
"age":19,
"address":"anhui"
}
return JsonResponse(json_values)
显示在页面内容: {"name": "xialei", "age": 19, "address": "anhui"}
5.FileResponse
文件内容的响应
5、快捷方式
1.render 方法:
必需的参数:
request:用于生成此响应的请求对象。
template_name:要使用的模板的全名或模板名称的列表。
可选参数:
context:要添加到模板上下文的值的字典。默认情况下,这是一个空字典。如果字典中的值是可调用的,视图将在渲染模板之前调用它。
content_type:用于生成文档的MIME类型。默认为DEFAULT_CONTENT_TYPE设置的值。
status:响应的状态码。默认为200。
using:用于加载模板的模板引擎名。
在settings的TEMPLATES中进行如下配置:
'DIRS': [os.path.join(BASE_DIR,"templates")],
'APP_DIRS': True,
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
在子项目views_app下创建templates文件夹,创建render_test.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>render_test模板</title>
</head>
<body>
render_test模板
</body>
</html>
在视图函数中传入模板参数:
from django.shortcuts import render
from django.views import View
def render_test(request):
return render(request,"render_test.html")
2.redirect 方法
通过传递一个URLConf调度器中配置path或re_path的名称,以及可选的一些位置或关键字参数,该URL将使用reverse()方法反向解析 :
在views_app.urls下配置路由:
from django.urls import path
from . import views
# 增加命名空间
app_name="views_app"
urlpatterns=[
# name参数为重定向寻找路由,从而寻找函数
# 含有参数
path("render_test/<int:index>",views.render_test,name="render_test"),
path("redirect_test/",views.redirect_test),
]
在views_app.views下配置函数:
from django.shortcuts import render,redirect
from django.views import View
def render_test(request,index):
return render(request,"render_test.html")
def redirect_test(request):
# 通过传入urls的render_test中name参数实现重定向
# 若重定向路由中有参数,则在redirect函数中必须传入参数
# 命名空间需要传入
return redirect("views_app:render_test",index=1)
默认情况下,redirect()返回一个临时重定向(302)。所有上述形式都接受permanent参数; 如果设置为True永久重定向(301)将被返回:
return redirect("views_app:render_test",index=1,permanent=True)
3.get_object_or_404,get_list_or_404
必需的参数:
klass:一Model类或一个Manager或QuerySet从哪个实例来获取对象
**kwargs:查找参数,应该采用get()或filter()的参数。
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from views_app.models import Question
def get_object_or_404_test(request,id):
question=get_object_or_404(Question,pk=id)
return render(request,'question.html',{"question":question})
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>question</title>
</head>
<body>
<p>get_object_or_404</p>
question_title:{{question.question_title}} <br>
question_text:{{question.question_text}} <br>
question_pub_date:{{question.question_pub_date}}
</body>
</html>
6、内置通用视图
包含在 from django.views import generic 中
具体视图类型有:
__all__ = [
'View', 'TemplateView', 'RedirectView', 'ArchiveIndexView',
'YearArchiveView', 'MonthArchiveView', 'WeekArchiveView', 'DayArchiveView',
'TodayArchiveView', 'DateDetailView', 'DetailView', 'FormView',
'CreateView', 'UpdateView', 'DeleteView', 'ListView', 'GenericViewError',
]
比较常用的:RedirectView、DetailView、ListView
例如:DetailView
使用类的方法:
urls.py:
# 参数必须规定为pk
path("question_detail/<int:pk>",views.QuestionDetail.as_view())
views.py:
from django.views import generic
class QuestionDetail(generic.DetailView):
model=Question
template_name='question_detail.html'
html:
<ul>
<li>question_title:{{object.question_title}}</li>
<li>question_text:{{object.question_text}}</li>
</ul>
使用函数的方法:
html:
<ul>
<li>question_title:{{question.question_title}}</li>
<li>question_text:{{question.question_text}}</li>
</ul>
urls:
path("question_detail_test/<int:id>",views.question_detail_func)
views:
def question_detail_func(request,id):
question=Question.objects.get(pk=id)
return render(request,'question_detail_func.html',{"question":question})