案例:用户登录

 一. urls.py文件里面创建URL和视图函数对应关系

from django.urls import path

from app01 import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    # www.xxx.com/index/  -> 函数
    path('index/', views.index),
    path('user/list/', views.user_list),
    path('user/add/', views.user_add),
    path('tpl/', views.tpl),
    # 联通新闻中心
    path('news/', views.news),
    # 请求和相应
    path('something/', views.something),

    # 用户登录
    path('login/', views.login),
    path('orm/', views.orm),
]

二. views.py文件中编写函数

from django.shortcuts import render, HttpResponse, redirect

def login(request):  # 用户登录
    if request.method == "GET":
        return render(request, "login.html")

    # 如果是POST请求,获取用户提交的数据
    # print(request.POST)
    username = request.POST.get("user")  # 获取输入值
    password = request.POST.get("pwd")

    # 目前是写死的,下一步是在数据库去取
    if username == 'root' and password == "123":  # 校验输入的值
        # return HttpResponse("登录成功")
        return redirect("http://www.chinaunicom.com.cn/")  # 重定向的网址

    # return HttpResponse("登录失败") 重新返回登录页面
    return render(request, 'login.html', {"error_msg": "用户名或密码错误"})  # 提示错误并渲染到页面

三. templates文件夹下创建login.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>用户登录</h1>
<form method="post" action="/login/">  <!-- post形式提交 -->
    {% csrf_token %}  <!-- 报错403 就把它加上 验证机制 -->
    <input type="text" name="user" placeholder="用户名">
    <input type="password" name="pwd" placeholder="密码">
    <input type="submit" value="提交"/>
    <span style="color: red;">{{ error_msg }}</span>  <!-- 提示错误 -->
</form>

</body>
</html>

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值