在视图中获取会话变量-Django

时间:2019-03-02 03:36:02

标签: django get django-forms django-views

如果用户刚刚在上一页中填写了表单,我正在尝试将GET请求值分配给symbol。我可以导航到其他页面并请求会话变量,但是当我返回索引时,它不再存在。

def index(request):


    if 'symbol' in request.GET:
        symbol = request.GET.get('symbol', '')
        request.session['symbol'] = symbol

    elif not request.session.get('symbol', 'none'):

        symbol = request.session['symbol']


    return render(request, 'backtests/earnings.html', {'symbol' : symbol})

我知道这段代码有一些问题,但是我真的不知道该从何处着手。到目前为止,我收到了错误

  

赋值之前引用的局部变量'symbol'

2 个答案:

答案 0 :(得分:0)

尝试这个

def index(request):
if request.method == "GET":
    symbol = request.GET.get('symbol', None)

    if symbol is not None or symbol != "":
        request.session['symbol'] = symbol
    else:
        symbol = request.session['symbol']
    return render(request, 'backtests/earnings.html', {'symbol': symbol})
else:
    redirect to path

答案 1 :(得分:0)

我知道了...

def index(request):

    if 'symbol' in request.GET:
        symbol = request.GET.get('symbol',' None')
        request.session['symbol'] = symbol

    else:
        symbol = request.session['symbol']