Rajesh Chamarthi
Rajesh Chamarthi

Reputation: 18818

django request.session.user in template

I am trying to use a custom User model and upon sign_in, I want to redirect the user to the homepage with the current user's information in the session. I ran the app in debug mode and checked session information in chrome dev tools. It looks like everything is set as required, but the template code is not able to read session information correctly

models.py

class User(AbstractBaseUser):
    name=models.CharField(max_length=255)
    email=models.CharField(max_length=255)
    slug = models.SlugField(unique=True, blank=True)
    .....

views.py

def sign_in(request):
    user=None
    # import pdb; pdb.set_trace();
    if request.method=='POST':
        form=SigninForm(request.POST)
        if form.is_valid():
            results=User.objects.filter(email=form.cleaned_data['email'])
            if len(results) == 1:
                if results[0].check_password(form.cleaned_data['password']):
                    request.session['user'] = results[0].pk
                    request.user=results[0]
                    return HttpResponseRedirect('/')
                else:
                .........

Template

    {% if user %} <!-- I have also tried request.session.user !>
      <li><a href="{% url 'sign_out' %}">Logout</a></li>
    {% else %}
      <li><a href="{% url 'sign_in' %}">Login</a></li>
      <li><a href="{% url 'register' %}">Register</a></li>
    {% endif %}

Debug session.

>>> from django.test import Client
>>> resp=Client().post('/sign_in/',{'email':'[email protected]','password':'anotherpassword2'})
> .../account/views.py(10)sign_in()
-> if request.method=='POST':
...
-> if len(results) == 1:
(Pdb) n
> .../account/views.py(15)sign_in()
-> if results[0].check_password(form.cleaned_data['password']):
(Pdb) n
> .../account/views.py(16)sign_in()
-> request.session['user'] = results[0].pk
(Pdb) n
> .../account/views.py(17)sign_in()
-> request.user=results[0]
(Pdb) n
> .../account/views.py(18)sign_in()
-> return HttpResponseRedirect('/')
(Pdb) request.session.user
*** AttributeError: 'SessionStore' object has no attribute 'user'
(Pdb) request.session['user']
9
(Pdb) user
(Pdb)

I also noticed that the session has some information, and this is what I get when I decode the info.

>>> from django.contrib.sessions.models import Session
>>> sess = Session.objects.get(pk='XXXX')
>>> print(sess.session_data)
.....
>>> print(sess.get_decoded())
{u'_auth_user_hash': u'XXXXX', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend', u'_auth_user_id': 1, u'user': 9}

>>> from django_project import settings
>>> settings.AUTH_USER_MODEL
'account.User'

Upvotes: 2

Views: 4985

Answers (1)

Ben
Ben

Reputation: 7124

request.session usually doesn't have a user object - double check by running p request.session.keys() in Pdb.

Depending on how you render your template* you can access the user via {% request.user %}.

{% user %} wont work, unless you specifically pass user to the template.

*https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render

Example:

in view:

from django.shortcuts import render

def foo(request):
    #...stuff
    return render(request, 'index.html', {})

in template

{% request.user %}

or

in view:

def foo(request):
    #...stuff
    user = request.user
    return render(request, 'index.html', {'user':user})

in template

{% user %}

Edit

If you want to check to see if the user is logged in you should use {% if user.is_authenticated %} in your template. Not {% if user %}

https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated

Upvotes: 3

Related Questions