Passing data between views

Hello, I have two views. From one view I want to pass data to the next view when redirected.

The data I wish to pass trough is portfolio_info

@login_required
def portfolio(request):

    form = PortfolioForm()
    if request.method == 'POST':
        #print('Printing post', request.POST)
        form = PortfolioForm(request.POST)

        if form.is_valid():
            instace = form.save(commit=False)
            instace.user = request.user
            instace.save()
            #form.save()


            portfolio_info = {
                'portfolio_name':instace.portfolio_name
            }
            
            print(portfolio_info['portfolio_name'])

            return redirect('transactions')

    context = {'form' : form}

    return render(request, 'backapp/portfolio.html', context)

To this view:

@login_required
def transactions(request):

    form = TransactionForm()
    if request.method == 'POST':
        #print('Printing post', request.POST)
        form = TransactionForm(request.POST)

        if form.is_valid():
            instace = form.save(commit=False)
            instace.save()

            return redirect('../')

    context = {
        'form' : form
    }
    return render(request, 'backapp/transaction.html', context)

As you can see, once the field is valid, the user is redirected. I want the user to be redirected with the portfolio_info.

Thanks for the help in advance! :slight_smile:

The redirect function takes keyword parameters in the function call.

Off-the-cuff - Iā€™m sure my syntax is wrong on one or more items here:

in a urls.py in your urlpatterns

path('transactions/<int:portfolio_id>/', views.add_transactions, name='add-transactions'),

your view can take the portfolio_id as a parameter:

def add_transactions(request, portfolio_id):
    ...

which means you want to:

return redirect('add-transactions', portfolo_id=portfolio_id_from_form_or_wherever)
3 Likes