【一】requests对象引入
【1】提交GET请求
前端
- form表单中action属性,如果不写的话,默认就是向当前路由请求
- form表单中的method属性,如果不写默认就是GET请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'jQuery.min.js' %}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
</head>
<body>
<h1 class="text-center">test页面</h1>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-offset-3">
<form action="" > 这里不写method属性 默认就是get属性
<p>username:<input type="text" class="form-control" name="username"></p>
<p>password:<input type="password" class="form-control" name="password"></p>
<p><input type="submit" class="btn btn-block btn-info"></p>
</form>
</div>
</div>
</div>
</body>
</html>
后端views文件代码
- 当我点击页面中的提交
- 后端控制台就会输出当前使用的方法
- 在示例中可以看到是get请求
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def test(requests):
res = requests.method #GET
print(res)
if requests.method == 'POST':
username = requests.POST.get('username')
password = requests.POST.get('password')
print(username, password)
return HttpResponse(f'{requests.method}')
return render(requests, 'test.html')
【2】提交POST请求
前端
- 在前端文件中,只需要修改from标签内的method属性值为post
- 就可以把这个form表单的请求方式改为POST请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'jQuery.min.js' %}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
</head>
<body>
<h1 class="text-center">test页面</h1>
<div class="container">
<div class="row">
<div class="col-lg-6 col-md-offset-3">
<form action="" method="post"> 修改为POST请求
<p>username:<input type="text" class="form-control" name="username"></p>
<p>password:<input type="password" class="form-control" name="password"></p>
<p><input type="submit" class="btn btn-block btn-info"></p>
</form>
</div>
</div>
</div>
</body>
</html>
后端
- 同样通过这个示例,可以看到确实是post请求
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def test(requests):
res = requests.method #POST
print(res)
if requests.method == 'POST':
username = requests.POST.get('username')
password = requests.POST.get('password')
print(username, password)
return HttpResponse(f'{requests.method}')
return render(requests, 'test.html')
注意
-
当前端from表单发送POST请求时,会报一个错,导致后端崩溃
-
只需要到配置文件中删除掉一行代码就可以
-
\# 'django.middleware.csrf.CsrfViewMiddleware',
【二】requests对象的属性
# 获取当前请求的方式
requests.method
# 获取POST方法提交的数据的字典对象
requests.POST
# 获取列表最后一个元素
requests.get
# 获取元素列表
requests.getlist
标签:username,框架,get,POST,Django,requests,password,method
From: https://www.cnblogs.com/Hqqqq/p/18094887