I’m trying to incorporate the user userID on the sidebar.
So the sidebar will show “Welcome username”
I’ve tried the cookie method but it doesn’t seem to work.
This is my cookie receiving my username:
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})
and this is my 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>
Am i doing anything wrong? Any help would be much appreciated.
Thank you.
Why so complicated?
You can check if user is logged in directly in template:
And check that in settings.py in TEMPLATE_CONTEXT_PROCESSORS have ‘django.contrib.auth.context_processors.auth’. Here is some docs