How can I get Javascript onSuccess response object variables in Python? - python

Background:
Working in a Django application, I have a template that performs an action (makes a payement) using an external API. The API call is done in Javascript.
On Success, the API returns a response object. This works well on tests.
function makePayment(applicationAmount) {
let paymentEngine = RmPaymentEngine.init({
key: 'abcd'
firstName: '{{ user.f_name }}',
onSuccess: function(response) {
console.log('callback Successful Response', response);
// TODO: Add a function to post the payment records to the database
// response from the API contains a dictionary like (read json) object
// how can I get that response object in Python and use those response
// object values to update a django model database records
},
onError: function(response) {
console.log('callback Error Response', response);
// TODO: Add a function to throw an error message
},
onClose: function() {
console.log("closed");
}
});
}
Question:
How can I get that onSuccess response object variables in Python and use those response object values to update a django model database records?
Looked at this link: How do I return the response from an asynchronous call? but can't seem to implement my need.
I'd be happy to be directed to a simple resource that explains the procedure, not something very involved that takes hours to understand.

Using ideas from #Lag11 and #Arount and a wonderful tutorial here, I created 2 function based views, one to just serve the 'page' the other to handle the 'page post to DB'.
Summary, I did this in the template:
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");
}
});
}
And this in the 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)

Related

Django is not loading the URL I defined

I am working on a project that generates dynamic urls, For ex. if I type 127.0.0.1:8000/newpage it generates a new model with slug newpage
Earlier the project was working fine but suddenly it started to show some bugs.
I am calling a URL using ajax like this (5th line):
$(document).on('click', '#save', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "text:update" %}',
data: {
newText: $('#text-content').val(),
slug: "{{ obj.slug }}",
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
if (json['status'] === 'OK') {
document.getElementById('msg-box').innerText = 'TEXT SAVED';
window.removeEventListener("beforeunload", beforeUnloadListener, { capture: true });
}
},
error: function (xhr, errmsg, err) {
}
});
});
It should load the view which I defined in the update url patterns but because of some reason it is still loading my slug view and generating a new url with slug update, I mean it shouldn't do that if I am telling it to load a specific view in URL pattern then why it is still loading slug view below is my urls.py:
#Only patterns
path('', home, name='home'),
path('<slug:slug>/', textview, name='textview'),
path('update/', update, name='update'),
views.py
def textview(request, slug):
obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'})
return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created})
def update(request):
if request.POST.get('action') == 'post':
slug = request.POST.get('slug')
text = request.POST.get('newText')
obj = Text.objects.get(slug=slug)
obj.text = text
obj.save()
response = JsonResponse({'status':'OK','text':text})
return response
Where are you using this AJAX code? If it is in a JavaScript file (.js), Jinja won't work there, so you have to write the absolute URL or you have to define a variable for the Jinja in the HTML and then use that variable in the JS file.
And try to add a slash after the URL if your APPEND_SLASH not True in settings.py.

Unable to render a template after using fetch in django

I have the following requirement:
Send data to backend using fetch()
receive the data in a view and render another template ( route to a different view)
The following is my code snippet:
JS:
fetch("/addpost", {
method: "POST",
body: JSON.stringify({ value: selecteddict }),
headers: {
"Content-type": "application/json;",
},
})
.then((res) => {
return res.text();
})
.then((text) => {
console.log(text);
});
// the data is being sent successfully
Django View1:
#csrf_exempt
def addpost(request):
if request.method == 'POST':
song = json.loads(request.body.decode('utf-8'))['value']
print(song)
# I want to redirect to another view called createpost that renders a new page
return JsonResponse({'status':201})
return render(request, 'addpost.html')
Django createpost view:
def createpost(request):
return render(request, 'createpost.html')
The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost
Please suggest a solution to this.
Your addpost view returns as JsonResponse in case of a POST request. If you want to redirect somewhere you need to use redirect() instead of JsonResponse()

How do I get data from my AJAX Post to my Django View?

This is what My ajax call looks like
$.ajax({
url:"{% url 'handsontable' %}",
data: {'getdata': JSON.stringify(hot.getData())},
dataType: 'json',
type: 'POST',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
This is what my django view looks like.
if request.method == 'POST':
request_getdata = request.POST.get('getdata', 'None')
return HttpResponse(request_getdata)
The alerts in ajax return the data and "success". But my HttpResponse returns "None".
Any idea why it is not passing the data through? Thanks!
First off you are trying to POST to a html file
url:"/utility_tool/decisions/solution_options/handsontable.html",
Instead, it should be a url to a view.
Second, the ajax post request should have the csrftoken in it's header and you can set it up like this:
<script type="text/javascript">
// using jQuery get csrftoken from your HTML
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
// if not safe, set csrftoken
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "{% url 'name of the view from urls.py' %}",
data: {
// here getdata should be a string so that
// in your views.py you can fetch the value using get('getdata')
'getdata': JSON.stringify(hot.getData())
},
dataType: 'json',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
And in your django view:
# views.py
from django.http import JsonResponse
def someView(request):
if request.method == 'POST':
# no need to do this
# request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
request_getdata = request.POST.get('getdata', None)
# make sure that you serialise "request_getdata"
return JsonResponse(request_getdata)
And in your urls:
# urls.py
urlpatterns = [
# other urls
path('some/view/', views.someView, name='name of the view in urls.py'),
]
I cannot add comments because I do not yet have up to 50 reputations as demanded by StackOverflow. This is supposed to be a comment under the answer provided by #abybaddi009. He has done a very good job thus far but the answer needs a finishing touch.
In the view
request_getdata = request.POST.get('getdata', None) does not work
but this does
body = request.body.decode('utf-8')
data = body[3]
request.body.decode('utf-8') returns a string which would look something like getdata=your_data you can then use string manipulation techniques or regex to extract your data.
What you need to do is :
code for ajax call ( in js file) to send the data to the view
jQuery.ajax(
{
'url': "url_pattern_in_urls_py_file/",
'type': 'POST',
'contentType': 'application/json; charset=UTF-8',
'data': JSON.stringify({'updated_data':your_data_val}),
'dataType': 'json',
'success': function ( return_data ) {
//success body
}
}
);
code in django view with respect to above POST ajax call to receive the data
import json
if request.method == 'POST':
updatedData=json.loads(request.body.decode('UTF-8'))
I added return false; at the end of the ajax request and it worked. I printed out the values in the view instead of using HttpResponse.

Django + Phonegap Authentication

I am building an application with Phonegap on the client side and a Django server on the backend. I am not able to authenticate the user. Here's my code.
$.ajax({
url: "http://192.168.0.101/userbase/login/",
type: "POST",
dataType: "json",
data: {"username": username,
"account": account,
"password": password,},
success: function (json) {
if (json.logged_in == true) {
window.location.href = "products.html";
}
else {
alert("Invalid Credentials. " + json.error);
}
}
});
This is the AJAX call to log in the user from the index.html. It is authenticated temporarily as in the views.py
# SOME CODE
login(request, user=user)
print(request.user.is_authenticated())
response = JsonResponse(response_data)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE'
response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type'
return response
prints True. But, when the window redirects to products.html and I make an AJAX request to my Django server and check if the user is authenticated or not, it returns False. I am not able to find the error.
Please help. Thanks.

django accept data from angularJS is not valid

I use angularJS $http send data to django and the method is POST
this is my controller.js
registerApp.controller('registerCtrl', function($scope, $http) {
$scope.submitRegisterForm = function() {
if ($scope.registerForm.$valid) {
console.log($scope.user);
$http({
method: 'POST',
url: '.',
data: $scope.user,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
} else {
return console.log(3333);
}
};
});
this is my views.py in django
if request.method == 'POST':
print request.POST
but the result of print is
<QueryDict: {u'{"username":"bob","password1":"123123","password2":"123123","email":"cot#q.com"}': [u'']}>
why the data is a Key of the dict?
and wher is the [u''] come from??
Just because you've called it form-encoded data, doesn't mean it actually is. In fact it looks like you're posting JSON. Drop that header and get the data by doing json.loads(request.body).

Categories

Resources