Shaon shaonty
Shaon shaonty

Reputation: 1415

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.

enter image description here

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

Upvotes: 0

Views: 2590

Answers (2)

Sabbir Ahmed
Sabbir Ahmed

Reputation: 349

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)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599530

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.)

Upvotes: 1

Related Questions