如何使用会话在Django中将字典从一个视图传递到另一个视图?

时间:2017-09-17 18:07:35

标签: python django session

我使用会话将dict从一个视图传递到另一个视图。但它显示了这个错误。我想创建多个模板提交表单。

enter image description here

我的 views.py

def view_qr_code(request, *args, **kwargs):
    # here i wanna retrive session data
    context = {
        'code': 'qrcode'
    }
    return render(request, 'add_send_product.html', context)


def send_product_add(request):
    form = SendProductForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            instance = form.save(commit=False)
            data_dict = instance.__dict__
            print data_dict
            request.session['s'] = data_dict
            return redirect('/qr-code/')

        else:
            messages.error(request, "Form is not valid")

    context = {
        'form': form,
        'headline': 'Delivery Item'
    }
    return render(request, 'add_send_product.html', context)

urls.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^send-product/add/$', views.send_product_add, name='add_send_product'),
    url(r'^qr-code/$', views.view_qr_code, name='qr_code'),
]

2 个答案:

答案 0 :(得分:1)

不要序列化模型实例。序列化表单的cleaned_data

(我不确定你在这里做了什么,因为你从不保存实例。如果你这样做,我会说你应该只在会话中存储新创建的实例的ID。)

答案 1 :(得分:0)

由于您不想在send_product_add()方法中保存数据,因此您只需在会话变量中存储request.POST数据

def view_qr_code(request, *args, **kwargs):
    # here i wanna retrive session data
    data_dict = request.session.get('saved')
    del data_dict['csrfmiddlewaretoken'] # middleware is not same here so 
    context = {
        'code': 'qrcode'
    }
    return render(request, 'add_send_product.html', context)


def send_product_add(request):
    form = SendProductForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            request.session['saved'] = request.POST
            return redirect('/qr-code/')

        else:
            messages.error(request, "Form is not valid")

    context = {
        'form': form,
        'headline': 'Delivery Item'
    }
    return render(request, 'add_send_product.html', context)