zoukankan      html  css  js  c++  java
  • Django首页显示用户名

    Django首页显示用户名

    实现效果图:

    编写前端页面:

    <tr v-if="username">
        <td>当前登录用户:[[username]]</td>
        <td><a href="/logout/">注销</a></td>
    </tr>
    <tr v-else="username">
        <td><a href="/login/">登录</a></td>
        <td><a href="/register/">注册</a></td>
    </tr>
    

    vue中需要绑定的变量:[[ username ]]

    实现原理:

    用户登录之后,保持登录状态,随后在cookie中添加登录信息。

    页面重定向到首页时,vue读取cookie。若cookie有用户名信息,则显示已登录状态,若没有,则显示未登录状态。

    配置路由:

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        url('^$', views.IndexView.as_view()),
    ]
    

    编写视图函数:

    from django.shortcuts import render
    from django.views import View
    
    class IndexView(View):
        def get(self, request):
            return render(request, 'index.html')
    

    获取cookie的js函数:

    // 获取cokie
    function getCookie(name){
        var r = document.cookie.match("\b" + name + "=([^;]*)\b");
        return r ? r[1] : undefined;
    }
    

    Vue:

    var vm = new Vue({
        el:'#app',
        delimiters:['[[', ']]'],
        data:{
            host, 
            username:''
        },
        mounted(){
            this.username = getCookie('username');
            console.log(this.username);
        },
        methods:{}
    });
    

    在登录及注册视图函数中设置cookie:

    # 登录状态保持
    login(request, user)
    
    # 响应
    response = redirect('/')
    response.set_cookie('username', user.username, max_age=60 * 60 * 24 * 14)
    return response
    

    源码

  • 相关阅读:
    一、left
    padding溢出
    一、
    Python创建、删除桌面、启动组快捷方式的例子分享
    openstack常见问题解决方法总结
    __attribute__ 详解
    __ATTRIBUTE__ 知多少?
    CentOS如何设置终端显示字符界面区域的大小
    shell使用技巧
    openstack 安全策略权限控制等api接口
  • 原文地址:https://www.cnblogs.com/lulujunsir/p/keep_login.html
Copyright © 2011-2022 走看看