Используя идеи из @ Lag11 и @Arount и замечательный учебник здесь , я создал 2 представления на основе функций, один для обслуживания «страницы», другой для обработки «пост страницы в БД».
Резюме, я сделал это в шаблоне :
function makePayment(applicationAmount) {
let paymentEngine = RmPaymentEngine.init({
key: 'abcd'
firstName: '{{ user.f_name }}',
onSuccess: function(response) {
console.log('callback Successful Response', response);
// start new additions
data = {
"payer_email": "{{ user.email }}",
"payer_phone": "{{ user.phone }}",
"payment_amount_total": response.amount,
}
$.ajax({
type: 'POST',
url: "{% url 'post_purchase_form' %}",
data: data,
onSuccess: function (response) {
console.log('callback db post Successful', response);
},
error: function (response) {
// alert the error if any error occured
alert(response);
}
})
// end new additions
},
onError: function(response) {
console.log('callback Error Response', response);
// TODO: Add a function to throw an error message
},
onClose: function() {
console.log("closed");
}
});
}
И это в views.py :
def application_form_view(request):
user = request.user
form = ApplicationForm(instance=user)
return render(request, 'application_form.html', {'form': form, 'user': user})
def post_application_form_view(request):
# request should be ajax and method should be POST.
if request.is_ajax and request.method == "POST":
# get the form data
form = ApplicationForm(request.POST, request.FILES)
# save the data and after fetch the object in instance
if form.is_valid():
instance = form.save()
# serialize in new FormPurchase object in json
ser_instance = serializers.serialize('json', [ instance, ])
# send to client side.
return JsonResponse({"instance": ser_instance}, status=200)
else:
# some form errors occured.
return JsonResponse({"error": form.errors}, status=400)
# some error occured
return JsonResponse({"error": "unknown errors"}, status=400)