Search code examples
javascriptpythondjangopaypal-ipndjango-paypal

Have a django reverse to a url with PK <int:pk>


I was following This Tutorial to set up payment with PayPal

my problem is with the paypal_dict as it contains this

paypal_dict = {
...
'return_url': 'http://{}{}/{}'.format(host,
                                           reverse('payment_done')),
...
}

and my payment_done URL needs to have an id for the trade itself, I'm not sure how can i have a pk within this Here is my full URLs.py

...
# Payment
    path('payment/process/<int:trade_id>/', payment_views.payment_process, name="payment_process"),
    path('payment/done/<int:trade_id>/', payment_views.payment_done, name="payment_done"),
...

My full process_paypal

def payment_process(request, trade_id):
    trade = get_object_or_404(Trade, id=trade_id)
    host = request.get_host()

    paypal_dict = {
        'business': settings.PAYPAL_RECEIVER_EMAIL,  # todo WHO TO PAY
        'amount': Decimal(trade.price),
        'item_name': trade.filename,
        'invoice': str(trade.id),
        'currency_code': 'USD',
        'notify_url': 'http://{}{}'.format(host,
                                           reverse('paypal-ipn')),
        'return_url': 'http://{}{}/{}'.format(host,
                                           reverse('payment_done')),
        'cancel_return': 'http://{}{}'.format(host,
                                              reverse('home')),
    }

    form = PayPalPaymentsForm(initial=paypal_dict)
    return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form})

Solution

  • You can pass trade_id in your url using args or kwargs.

    paypal_dict = {
    ...
    'return_url': 'http://{}{}'.format(host,
          reverse('payment_done', kwargs={'trade_id': trade.id})),
    ...
    }
    

    docs ref