1.HttpResponce函数
HttpResponce(content,content_type=None,status=None,charset=None,*args,**kwargs)
content:返回给视图函数的内容
content_type:返回给视图函数的类型
- text/html HTML文本
- text/plain 纯文本
- text/css
- text/javascript
- application/xml xml文本
- application/json json文本
- multipart/form-data 上传文本
status:HTTP响应代码
charset:字符编码设置
2.重新定义404页面
settings里面DEBUG需要改成False,ALLOWED_HOSTS = [’*’]需要随便指定一个值
3.http请求方式
1 GET 请求指定的页面信息,并返回实体主体。
2 HEAD 类似于 GET 请求,只不过返回的响应中没有具体的内容,用于获取报头
3 POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST 请求可能会导致新的资源的建立和/或已有资源的修改。
4 PUT 从客户端向服务器传送的数据取代指定的文档的内容。
5 DELETE 请求服务器删除指定的页面。
6 CONNECT HTTP/1.1 协议中预留给能够将连接改为管道方式的代理服务器。
7 OPTIONS 允许客户端查看服务器的性能。
8 TRACE 回显服务器收到的请求,主要用于测试或诊断。
9 PATCH 是对 PUT 方法的补充,用来对已知资源进行局部更新 。
4.视图装饰器
require_http_method([method_list])
require_GET() 只允许使用get方式请求
require_POST() 只允许使用post方式请求
require_safe() 只允许使用get方式和head方式请求
5.render:渲染的用法
render(request, template_name,context=None,content_type=None,status=None,using=None)
必选参数:
request:生成httpresponce对象
template_name:指定你需要渲染的模板名称
可选参数:
context:上下文,必须是一个字典,我们在html中使用它的key,通过key展示相应的value
content_type:指定上下文的类型
- text/html HTML文本
- text/plain 纯文本
- text/css
- text/javascript
- application/xml xml文本
- application/json json文本
- multipart/form-data 上传文本
status:响应的状态码
using:用于加载模块的引擎名称
**主urls.py**
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('news.urls'))
]
**app里的urls.py**
from django.contrib import admin
from django.urls import path
# from django.conf.urls import handler404
from . import views
urlpatterns = [
path('',views.Indexview.as_view(),name="index"),
# path('index/',views.index),
# path('incex/home/',views.index)
]
# handler404 = views.page_error##需要写在外面
**views.py**
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django.views.decorators.http import require_http_methods
# Create your views here.
@require_http_methods(['GET','POST'])##必须要有这个list,不写GET会报405错误
def index(request):
# http_list=[
# '<h1>请求协议: <span style="color:red">%s</span></h1>'%request.scheme,
# '<h1>地址: <span style="color:red">%s</span></h1>' % request.get_host(),
# '<h1>端口: <span style="color:red">%s</span></h1>' % request.get_port(),
# '<h1>请求方式: <span style="color:red">%s</span></h1>' % request.method,
# '<h1>完整的URL: <span style="color:red">%s</span></h1>' % request.get_raw_uri(),
# '<h1>编码: <span style="color:red">%s</span></h1>' % request.encoding,
# ]
# return HttpResponse("欢迎光临此页面")
return render(request,'search.html')
#类视图
class Indexview(View):
def get(self,request):
return render(request,'404.html')
# def page_error(request,exception):
# return render(request,'404.html')
**templates**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>您访问了错误的网站</h1>
</body>
</html>