Skip to content Skip to sidebar Skip to footer

How Do I Pass A List From One View To Another In Django?

I've been scouring StackOverflow, but I haven't found an answer to this that works for me. I am relatively new to Python and Django, so maybe I'm thinking about it wrong. To make

Solution 1:

That is exactly what the session is for. In view 1:

request.session['list'] = list_to_process

And in view 2:

list_to_process = request.session['list']

Solution 2:

If you are willing to use session then go with the answer given by @Daniel,

But in your case it seems that you are not going on separate url, you just need to render it in the same url but need the output from that view, in that case take help from named paramter of python functions like this -

defview2(request, list_to_process=None, **kwargs):

     use list_to_process to manufacture formset (e.g. make a formset with one entry for each item in the list)
     return render(request, 'Project/template2.html', {'formset': formset})

defview1(request):

    if request.method == "POST":
        if form.is_valid():
            result = form.cleaned_data
            list_to_process = []
            for item in result:
                list_to_process.append(item)
            return view2(request, list_to_process=list_to_process)
    else:
        .....

The benefit of using named parameter is that, they are optional and thus will not throw error if they are not provided, for example, when that view is called directly instead from inside view1

Post a Comment for "How Do I Pass A List From One View To Another In Django?"