第三单元 视图层

本文详细介绍了Django视图如何处理GET和POST请求,包括解析参数、返回响应及创建表单页面。同时,展示了如何在CBV(类视图)中使用get和post方法,并利用重定向实现页面跳转。文中还提及了注册和登录的示例,以及在模板中创建表单的HTML代码。
摘要由CSDN通过智能技术生成

视图请求

特点

视图函数一般用来接收一个Web请求HttpRequest,
之后返回一个Web响应HttpResponse

组成

  • get
  • post
    <注意>
    GET一般用于获取/查询资源信息,
    而POST一般用于更新资源信息

get,post请求处理

—需要的导包 from django.http import HttpResponse

解析get请求

def MyView(request):
    page = request.GET.get('page')
    id = request.GET.get('id')
    return HttpResponse(f'这是第一个视图,当前的页数为{page},id为{id}')

解析post请求

def MyView2(request):
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    return HttpResponse(f"这是第二个视图,账号{user},密码{pwd}")

返回带有表单的页面

在post基础上使用

def IndexView(request):
    return render(request,'index.html')

在templates里创建index.html,在里面创建表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>表单页面</h3>
    <form method="post" action="/myview2/">
        {% csrf_token %}
        账号:<input type="text" name="user">
        密码:<input type="password" name="pwd">
        <input type="submit" value="提交">
    </form>
</body>
</html>

重定向redirect

使用前必须导入模块:

from django.shortcuts import render,redirect

类似于vuex里面的页面跳转,一般用于试图代码中

CBV实例运用

FBV一般是通过函数直接定义的,而CBV是将多种不同功能的函数整合到类中,来进行编写视图的功能。

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):		<2>
        user1 = request.POST.get('user')
        pwd1 = request.POST.get('pwd')
        try:
            Users.objects.create(user=user1,pwd=pwd1)
        except Exception as e:
            print(e)
            return HttpResponse("注册失败")
        return redirect('/login/')		<1>

class LoginView(View):
    def get(self,request):		
        return render(request,'login.html')
    def post(self,request):		<2>
        user1 = request.POST.get('user')
        pwd1 = request.POST.get('pwd')
        try:
            user_data = Users.objects.get(user=user1)
        except Exception as e:
            print(e)
            return HttpResponse("账号密码不存在")
        if pwd1 == user_data.pwd:
            return redirect('/index/')		<1>
        else:
            return HttpResponse('密码错误')

class IndexView(View):
    def get(self,request):
        return render(request,'index.html')

PS:
<1> 运用重定向
<2>运用post和get发出请求以保存或提取账号密码。

CBV使用注意

- 对应路由此时设置为,需要使用试图类的as_view()函数进行实例化
- 类中函数必须为小写
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值