from django import views
class View(views.View):
def get(self, request):
print('GET方法')
return HttpResponse('GET方法')
def post(self, request):
print('POST方法')
return HttpResponse('POST方法')
from django.views.generic import TemplateView
urlpatterns = [
path('xxx', views.View.as_view()),
path('yyy', TemplateView.as_view(template_name='kanyun/2.html'))
]
前端页面,点击发送,表单提交地址为,路由中的xxx,如果是post请求则返回post函数中的结果,如果是get请求则返回get函数中的结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/kanyun/xxx" method="post">
{%csrf_token%}
<button type="submit">发送</button>
</form>
</body>
</html>
from django.views.decorators.http import require_GET, require_http_methods, require_POST
# 只能接收get的请求,如果是post请求访问则直接报错,无法接收
@require_GET
def rgt(request):
return HttpResponse('GET请求')
# 只能接收post的请求,如果是get请求访问则直接报错,无法接收
@require_POST
def rpt(request):
return HttpResponse('POST请求')
# 可以接收到列表中的规定的请求,列表中的情爱u方法必须大写
@require_http_methods(['GET', 'POST'])
def gpt(request):
return HttpResponse('收到')
def check(request):
if request.method == 'POST':
return HttpResponse('我是post请求')
elif request.method == 'GET':
return HttpResponse('我是get请求')
原文:https://www.cnblogs.com/tiaowangdeying/p/10508050.html