1、什么是视图
vi app_demo/views.py
from django.http import HttpResponse
def login(request): #定义视图函数时传入的第一个参数必须是request
return HttpResponse("登录页面") #视图函数的结尾必须有一个return 去响应web请求
小结
2、request 请求对象
案例1 GET
vi app_demo/views.py
from django.http import HttpResponse
def login(request):
name = request.GET.get("name")
return HttpResponse(name)
vi app_demo/urls.py
from django.urls import path,re_path
from . import views
urlpatterns = [
path("login/", views.login),
]
访问测试
#带k/v去请求 浏览器默认访问的请求格式为GET
http://127.0.0.1:8000/login/?name=123
#不带k/v请求
http://127.0.0.1:8000/login
案例2 method
vi app_demo/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("login/", views.login),
path("index/", views.index)
]
vi app_demo/views.py
from django.http import HttpResponse
from django.shortcuts import render
def login(request):
name="GET"
if request.method == "POST":
name="POST"
return HttpResponse(name)
return HttpResponse(name)
def index(request):
return render(request,'login.html')
vi templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/login/" method="post">
<input type="text" id="username" name="username" align="center">
<input type="password" id="password" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
可能出现的报错403
vi Django_demo/Django_demo/settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
#将django.middleware.csrf.CsrfViewMiddleware 删掉即可
运行程序
案例3 POST
vi app_demo/views.py
from django.http import HttpResponse
from django.shortcuts import render
def login(request):
user = ""
passwd = ""
if request.method == "POST":
user = request.POST.get("username")
passwd = request.POST.get("password")
return HttpResponse(user+passwd)
#requests.post(***) 发送请求 post必须是小写的
#request.POST.get() 是用来获取数据的
def index(request):
return render(request,'login.html'
3、request 的其他方法
4、QueryDict对象
QueryDict方法
5、使用案例
from django.http import QueryDict
from django.shortcuts import render
from django.views.decorators.http import require_POST
@require_POST
def handle_post(request):
# 获取 POST 请求的 QueryDict 对象
post_data = request.POST
# 获取 QueryDict 对象中的值
username = post_data.get('username')
password = post_data.get('password')
# 使用 QueryDict 对象的方法操作值
post_data.setdefault('gender', 'male')
post_data.appendlist('hobby', 'reading')
# 返回响应
return render(request, 'result.html', {'username': username, 'password': password})
说明