如何在django中设置和获取会话变量?

时间:2021-11-27 23:07:55

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?

如何获得会话的“idempresa”值,以便在查询集中使用?

2 个解决方案

#1


44  

For setting session variable:

设置会话变量:

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

For getting session Data:

获得会话数据:

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

#2


34  

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/

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

#1


44  

For setting session variable:

设置会话变量:

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

For getting session Data:

获得会话数据:

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

#2


34  

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/

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