前后端交互
form表单提交数据的三个要素
1. form标签必须要有action和method属性
2. 所有获取用户输入的标签必须放在form表单中,必须要有name属性
3. 必须要有submit按钮
<form class="form-horizontal" action="/login/" method="post"> <div class="col-sm-9"> <h2 class="text-center">请登录</h2> </div> <div class="form-group"> <div class="col-sm-9"> <div class="input-group margin-bottom-sm"> <label for="email" class="hidden">邮箱</label> <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span> <input class="form-control" name="email" type="text" id="email" placeholder="您的邮箱地址"> </div> <span class="help-block"></span> </div> </div> <div class="form-group"> <div class="col-sm-9"> <div class="input-group"> <label for="password" class="hidden">密码</label> <span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span> <input class="form-control" name="pwd" type="password" id="password" placeholder="请输入密码"> </div> <span class="help-block"></span> </div> </div> <div class="form-group"> <div class="col-sm-9"> <div class="checkbox"> <label> <input type="checkbox"> 记住我 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-9"> <button type="submit" id="b1" class="btn btn-block btn-primary">登录</button> <p style="color: red;text-align: center">{{ error_msg }}</p> </div> </div> </form>
def login(request): # print(request.GET) # print('-' * 120) error_msg = '' # 需要判断 # 根据请求的方法来做判断 if request.method == 'POST': # 如果是第二次来,表示填完了要给我发数据了 --> POST email = request.POST.get('email') pwd = request.POST.get('pwd') print(email, pwd) # if email == '1@1.com' and pwd == '123': # 从数据库查询有没有这个用户 # select * from app01_user where email='1@1.com' and pwd='123'; ret = User.objects.filter(email=email, pwd=pwd) print(type(ret[0])) print(ret[0].id, ret[0].email, ret[0].pwd) if ret: # 登录成功 # 跳转到路飞学城 # return redirect('https://www.luffycity.com') # return render(request, 'index.html') return redirect('/index/') else: # 登录失败 # 提示用户邮箱或密码错误 error_msg = '邮箱或密码错误' # 如果你是第一次来,是跟我要一个登录页面用来填写数据的 --> GET return render(request, 'login.html', {'error_msg': error_msg})
参考至盗版网课教材,如有侵权,老师你懂的