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

gorkyyrv  于 2023-02-10  发布在  Go
关注(0)|答案(3)|浏览(182)

我需要在会话中设置一个变量,当用户登录时,我该怎么做?

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

我的另一个问题是:

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

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

我怎样才能获得session的“idempresa”值,以便在我的查询集中使用?

w9apscun

w9apscun1#

设置会话变量:

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

获取会话数据:

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

ny6fqffe2#

设置会话变量:

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

用于获取会话数据

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

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

hc2pp10m

hc2pp10m3#

您可以通过**“request.session['key']"设置和获取session**,如下所示:

# "myapp/views.py"

from django.shortcuts import render

def my_view(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
    return render(request, 'myapp/index.html', {})

然后,您可以在Django Template上获得session,如下所示:

# "myapp/index.html"

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

相关问题