Django 实现登陆后跳转

说明

实现网页登陆后跳转应该分为两类:即登陆成功后跳转登陆失败再次登陆成功后跳转。参考网上内容,基本都只实现了第一类。而没有实现第二类。html

实现

为了能让登陆失败后再次登陆成功后还能实现跳转。我这里采用了笨办法, 即:不管登陆成功与否,都将跳转连接在先后端进行传递 ,这样跳转连接就不会在登陆失败后消失。很少说,上代码前端

后端 views.py

from django.shortcuts import render, redirect

def login(request):
    # 当前端点击登陆按钮时,提交数据到后端,进入该POST方法
    if request.method == "POST":
        # 获取用户名和密码
        username = request.POST.get("username")
        passwd = request.POST.get("password")
        # 在前端传回时也将跳转连接传回来
        next_url = request.POST.get("next_url")

        # 对用户进行验证,假设正确的用户名密码为"aaa", "123"
        if username == 'aaa' and passwd == '123':
            # 判断用户一开始是否是从login页面进入的
            # 若是跳转连接不为空而且跳转页面不是登出页面,则登陆成功后跳转,不然直接进入主页
            if next_url and next_url != "/logout/":
                response = redirect(next_url)
            else:
                response = redirect("/index/")
            return response
        # 若用户名或密码失败,则将提示语与跳转连接继续传递到前端
        else:
            error_msg = "用户名或密码不正确,请从新尝试"
            return render(request, "app/login.html", {
                'login_error_msg': error_msg,
                'next_url': next_url,
            })
    # 若没有进入post方法,则说明是用户刚进入到登陆页面。用户访问连接形以下面这样:
    # http://host:port/login/?next=/next_url/
    # 拿到跳转连接
    next_url = request.GET.get("next", '')

    # 直接将跳转连接也传递到后端
    return render(request, "autotest/login.html", {
        'next_url': next_url,
    })

前端页面 login.html

<form action="{% url 'login' %}" method="post">
                 <h1>请使用xxx登陆</h1>
                 <div>
                   <input id="user" type="text" class="form-control" name="username" placeholder="帐户" required="" />
                 </div>
                 <div>
                   <input id="pwd" type="password" class="form-control" name="password" placeholder="密码" required="" />
                 </div>
       // 注意这里多了一个input。它用来保存跳转连接,以便每次点击登陆按钮时将跳转连接传递回后端
       // 经过display:none属性将该input元素隐藏起来
                   <div style="display: none;">
                       <input id="next" type="text" name="next_url" value="{{ next_url }}" />
                   </div>
       // 判断是否有错误提示,如有则显示
                   {% if login_error_msg %}
                       <div id="error-msg">
                           <span style="color: rgba(255,53,49,0.8); font-family: cursive;">{{ login_error_msg }}</span>
                       </div>
                   {% endif %}
                 <div>
                     <button type="submit" class="btn btn-default" style="float: initial; margin-right: 60px">登陆</button>
                 </div>
   </form>

总结

其实这种实现方式就是让跳转连接在先后端交互中不损失掉。固然也能够在前端不用form元素,直接用ajax的post形式,而后让跳转在前端的ajax逻辑中执行。python

相关文章
相关标签/搜索