How can I set and get session variable in django?

DjangoSession

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

For setting session variable:

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

For getting session Data:

if 'idempresa' in request.session:
	idempresa = request.session['idempresa']

Solution 2 - Django

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfh_bashView Question on Stackoverflow
Solution 1 - DjangoVarnan KView Answer on Stackoverflow
Solution 2 - DjangoArunView Answer on Stackoverflow