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 a simple example, imagine two views with different associated URLs. This is not supposed to be perfect code. I'm just trying to figure out how to get a variable-length list of items from view 1 into view 2. I don't see a way to do it via the URL because the list may be variably long. Shouldn't this be extremely easy to do?
def view2(request, list_to_process):
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})
def view1(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)
*WHAT CODE DO I USE HERE TO CALL VIEW2 AND SEND IT list_to_process AS AN ARGUMENT OR REQUEST ADDITION?*
else:
formset = formsettype()
helper = AssayHelper() (defined elsewhere)
helper.add_input(Submit("submit", "Submit")
return render(request, 'Project/template1.html', {'formset': formset, 'helper': helper})
Can someone please help? Thanks.
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']
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 -
def view2(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})
def view1(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With