73

I need to set a variable on session, when a user login happens. How can I do this?

if request.user.is_authenticated():
    profile = request.user.get_profile()
    request.session['idempresa'] = profile.idempresa

My other question is in a form:

class PedidoItensForm(ModelForm):
    class Meta:
        model = ItensPedido

    def __init__(self, *args, **kwargs):
        profile = kwargs.pop('vUserProfile', None)
        super(PedidoItensForm, self).__init__(*args, **kwargs)

How can I get the "idempresa" value of session, to use in my queryset?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
fh_bash
  • 1,725
  • 4
  • 16
  • 23
  • Edit: this line: profile = kwargs.pop('vUserProfile', None) doesn`t work... I cannot know how to pass vUserProfile when I use inlineformset_factory, if I get how to pass vUserProfile using inlineformset_factory, this problem is solved! – fh_bash Jan 22 '13 at 19:02
  • 1
    1: Build your own middleware. Or put it wherever authentication happens. https://docs.djangoproject.com/en/dev/topics/http/middleware/ 2: Ask new questions in a new question. – Yuji 'Tomita' Tomita Jan 22 '13 at 19:57

3 Answers3

99

For setting session variable:

request.session['idempresa'] = profile.idempresa

For getting session Data:

if 'idempresa' in request.session:
    idempresa = request.session['idempresa']
Varnan K
  • 1,237
  • 8
  • 16
  • 4
    @slavugan Django sessions don't have a save() method. They are saved automatically when changed, or you can force a save by setting `request.session.modified` to `True`. – voodoo-burger Jan 08 '17 at 01:24
  • You can use session in templates like this `{{ request.session.idempresa }}` – Kaz Miller Mar 08 '22 at 15:40
65

For setting session variable:

request.session['fav_color'] = 'blue'

For getting session Data

fav_color = request.session.get('fav_color', 'red')

Reference: https://docs.djangoproject.com/en/dev/topics/http/sessions/

arulmr
  • 8,620
  • 9
  • 54
  • 69
Arun
  • 1,149
  • 11
  • 22
2

You can set and get session with request.session['key'] and get session with request.session.get('key') in Djanog Views as shown below. *request.session.get() returns None by default if the key doesn't exist and you can change None to other value like Doesn't exist by setting it to the 2nd argument as shown below and you can see When sessions are saved and you can see my question and my answer explaining when and where session is saved:

# "views.py"

from django.shortcuts import render

def test(request):
    request.session['person'] = {'name':'John','age':27}
    print(request.session['person']) # {'name':'John','age':27}
    print(request.session['person']['name']) # John
    print(request.session['person']['age']) # 27
    print(request.session.get('person')) # {'name':'John','age':27}
    print(request.session.get('person')['name']) # John
    print(request.session.get('person')['age']) # 27
    print(request.session.get('animal')) # None
    print(request.session.get('animal', "Doesn't exist")) # Doesn't exist
    return render(request, 'index.html', {})

And, you can get session with request.session.key in Django Templates as shown below:

# "templates/index.html"

{{ request.session.person }}      {# {'name':'John','age':27} #}
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }}  {# 27 #}

And, you can delete session with the code below. *request.session.pop('key') can get, then delete session and error occurs if the key doesn't exist and the 2nd argument is not set and if the key doesn't exist and the 2nd argument is set, the 2nd argument is returned and request.session.clear() and request.session.flush() can delete all the current session and you can see my question and the answer explaining the difference between request.session.clear() and request.session.flush():

# "views.py"

from django.shortcuts import render

def test(request):
    del request.session['person']
    del request.session['person']['name']
    del request.session['person']['age']
    print(request.session.pop('person')) # {'name':'John','age':27}
    print(request.session.pop('animal') # Error
    print(request.session.pop('animal', "Doesn't exist")) # Doesn't exist
    request.session.clear()
    request.session.flush()
    return render(request, 'index.html', {})
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129