1

Im working with django and i would like to store a object (in session?) so i can use this in multiple templates. So similar to the "user" that is always accessible, id like to add one of my own. So i dont have to add it every time in render(request,

What i try so far:

def login_character(request, character_name):
    request.session['character'] = Character.objects.get(name=character_name)
    return HttpResponseRedirect(reverse('index'))

Template:

{% if 'character' in request.session %}
    <p>Jeej there is some character</p>
    {{ request.session.character.name }}
{% else %}
    <p>Nope, nothing here</p>
{% endif %}

But that doesn't seem to work, Can someone help me out or point in the right direction?

With kind regards, Hans

Hans de Jong
  • 2,030
  • 6
  • 35
  • 55
  • I recommend reading a little about sessions and [how to use them in django](https://docs.djangoproject.com/en/dev/topics/http/sessions/) – yuvi Nov 27 '13 at 19:53

1 Answers1

3

I think you meant

{% if 'character' in request.session %}

instead of

{% if 'character' in request.session['character'] %}

Also, you wrote that you need sessions, because you want an object to be always accessible, without a need to explicitly add it in every view. In this case I think a template context processor would probably be a better choice.


Update: You also need to make sure that django.core.context_processors.request is among template context processors in your settings file. See also this answer.

Community
  • 1
  • 1
Ludwik Trammer
  • 24,602
  • 6
  • 66
  • 90