简体   繁体   中英

How do I pass a dictionary from one view to another in Django using session?

I have used session to pass dict from one view to another. But it shows this error. I want to create multiple templates submit form.

在此处输入图片说明

my 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'),
]

Don't serialize the model instance. Serialize the form's cleaned_data .

(I'm not sure what you are doing here, since you never save the instance anyway. If you did, I would say that you should just store the ID of the newly-created instance in the session.)

As you don't want to save data in send_product_add() method so you just store request.POST data in your session variable

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM