Python web模版Django-09 处理“发布会管理登陆页面”上获取的登陆账号和密码

对于输入的密码和账号,我们需要进行处理,专门在views中写一个方法 login_action,登陆密码和账号输入正确的话,提示成功,登陆失败,在页面上提示失败。


step1: 就目前的知识来看,views下的方法一定要对应一个页面,就在urls.py中加入一个 login_action/的路径

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('login_action/', views.login_action)
]

step2: 在views.py中加入如下代码

def login_action(request):
    # request = HttpRequest(request)   # 这个是为了方便在pycharm中自动带出request下的方法,用完后就注释掉
    username = request.POST.get('username', '')  # HttpRequest下的方法可以到这里参考 https://www.cnblogs.com/LiCheng-/p/6920900.html
    password = request.POST.get('password', '')
    if username == 'admin' and password == '123456':
        return HttpResponse("Login success")
    else:
        return render(request, 'index.html', {'wronglyInput': '用户名或密码输入错误!'}) 

step3 : 更新index.html ,让其能处理wronglyInput并同时响应login_action

 {'wronglyInput': '用户名或密码输入错误!'}

  • 这是一个字典,要让其字符显示到页面页面上,还需要在index.html中加一句代码, 这里不能加引号,wronglyInput就是key名
  • 另外要让这个post与login_action关联起来,还需要加入 action="/login_action/"  (主要必需前后都加"/")


step4: 运行结果

这里如果校验成功,返回一个页面 http://localhost/login_action/, 直接用HttpResponse打印 Login success


如果校验失败,同样返回页面http://localhost/login_action/,但其展示的内容与'index.html'基本一致,只是加了一个错误提示信息 


猜你喜欢

转载自blog.csdn.net/pansc2004/article/details/80485295