如何从登录页面传递用户名并使其显示在侧栏上

Sta*_*iow 1 html python django

我正在尝试将用户userID合并到侧边栏上.

所以侧边栏会显示"欢迎用户名"

我尝试过cookie方法,但似乎没有用.

这是我的cookie收到我的用户名:

def login_user(request):
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
                cookie = Cookie.SimpleCookie()
                cookie['username']=str(time.time())
                return render_to_response('r2/topic/index.html',{})
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."
            return render_to_response('registration/login.html',{'state':state, 'username': username})

    return render_to_response('registration/login.html',{'state':state, 'username': username})
Run Code Online (Sandbox Code Playgroud)

这是我的index.html:

                  <!-- sidebar -->
        <div id="sidebar">
            <div class="about-me">
                <h3>Welcome {{ username }}</h3> 
        <script type="text/javascript">
        function getCookie(c_name)
        {
          var i,x,y,ARRcookies=document.cookie.split(";");
          for (i=0;i<ARRcookies.length;i++)
            {
                x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
                y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
                x=x.replace(/^\s+|\s+$/g,"");
                if (x==c_name)
                    {
                        return unescape(y);
                    }
            }
        }


        function checkCookie()
        {
          var username=getCookie("username");
          if (username!=null && username!="")
            {

                <h3>document.getElementById("about-me").innerHTML = "Welcome " +username;</h3>
            }
          else 
            {
                username=prompt("Please enter your name:","");
                if (username!=null && username!="")
                        {
                            setCookie("username",username,365);
                        }
            }
        }
        </script>
Run Code Online (Sandbox Code Playgroud)

我做错了吗?任何帮助将非常感激.

谢谢.

小智 6

为什么这么复杂?您可以检查用户是否直接在模板中登录:

{% if user.is_authenticated %}
   Hello {{ user.username }}
{% else %}
   Please log in
{% endif %}
Run Code Online (Sandbox Code Playgroud)

并检查TEMPLATE_CONTEXT_PROCESSORS中的settings.py中是否有'django.contrib.auth.context_processors.auth'.这是一些文档