Accessing Django View data fro JavaScript using Fetch Api - python

I'm trying to get data from Django view using fetch API but the fetch API isn't reaching the Django view.
function connect(username) {
alert('connect');
let promise = new Promise((resolve, reject) => {
// get a token from the back end
let data;
alert("before append")
// data.append('csrfmiddlewaretoken', $('#csrf-
helperinput[name="csrfmiddlewaretoken"]').attr('value'));
alert("vc")
fetch("/videocall/", {
method: 'POST',
// headers: {
// "X-CSRFToken": getCookie("csrftoken"),
// "Accept": "application/json",
// "Content-Type": "application/json"
// },
headers:{
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax()
'X-CSRFToken': csrftoken,
},
//credentials: "same-origin",
body: JSON.stringify({'username': username})
}).then(res => res.json()).then(_data => {
// join video call
alert("Joint")
data = _data;
return Twilio.Video.connect(data.token);
}).then(_room => {
alert("room")
room = _room;
room.participants.forEach(participantConnected);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
connected = true;
updateParticipantCount();
connectChat(data.token, data.conversation_sid);
resolve();
}).catch(e => {
alert("catch")
console.log(e);
reject();
});
alert(promise)
});
return promise;
};
Here's my django view
def videocall(request):
print("Trying to login")
if request.method == "POST":
print("Trying to login")
It's not even printing trying to login which i printed in django view. I think there's some problem in URL in fetch.
I'm new to Django please help me in this regard

I had a similar issue but this code below is working fine both for get and post requests in Django 3.1.4 and Python 3.8.
//js
const AssignStaffForm = () => {
fetch('/app/get_users/', {
method: "GET",
credentials: "same-origin",
headers: {
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRFToken": getCookie("csrftoken"),
},
})
.then((res) => res.json())
.then((data) => {
// then I use this data in an html form.
console.log(data)
})
.catch((err) => {
console.log("err in fetch", err);
});
};
#url dispatcher
path('get_users/', views.get_users, name='get_users'),
#view
import json
from django.http.response import HttpResponse
def get_users(request):
if request.method == 'GET':
users=[]
for user in User.objects.all():
users.append({'id':user.id, 'name': user.get_full_name()})
data = json.dumps({'users': users})
return HttpResponse(data, content_type='application/json')
Note:
I had earlier split my views and forgot to delete the original view functions from the main view file and this seemed to be the cause of the error in my case.

Related

How can I get from Flask data before the return

so i want to make something like a progress bar in js(react) and in python(flask)
and I want to return to the react that he needs to change the progress bar.
React:
fetch(pythonUrl+"/NormalMyProgress",
{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams(
{
"text" : "hello"
})
})
.then(resp => resp.json())
.then(data =>
{
setProgressBarValue(data.data)
})
python:
#app.route('/NormalMyProgress',methods=["POST"])
def home_normal():
txt = request.form.get('text')
print(txt)
for i in [0,25,50,100]
return jsonify({"data":i})

How can I "translate" a node.js request to Python?

basically I've got the following code:
var fs = require('fs');
const request = require("request");
var body = JSON.parse(fs.readFileSync('body.json', 'utf8'));
var options = {
method: 'POST',
uri: 'https://api.pagar.me/core/v5/orders',
headers: {
'Authorization': 'Basic ' + Buffer.from("sk_test_*:").toString('base64'),
'Content-Type': 'application/json'
},
json : body
};
request(options, function(error, response, body) {
console.log(response.body);
});
I've tried to do the following in Python:
import requests
headers = {'Authorization': 'token',
'Content-Type': 'application/json'
}
k = requests.post("https://api.pagar.me/core/v5/orders", headers=headers)
The node code works, but the python only returns 401, so I know the token is right as the node example works, what do I need to do here I'm a newbie.

Error trying to save data in django via ajax(fetch)

I have a model that references other models, I am trying to save data using ajax
Example:
class Friend(models.Model):
name = ...
class Main(models.Model):
name = ....
friend = models.ForeignKey(Friend, on_delete=models.CASCADE)
All body comes from ajax(fetch) request
I have a table (html), and add data to cells, then with the
enter event, send data.
Like this:
input.addEventListener("keyup", function (e) {
//in this scenario I already have the whole row
// get full_row `row_data`
post_ajax = {
method: "POST",
headers: {
"X-CSRFToken": crf_token, // I get it with a regular expression
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Accept: "application/json",
},
body: JSON.stringify(row_data),
};
fetch("my_url", post_ajax)
.then((res) => res.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success:", response));
});
My view function
def save_post(request):
if request.is_ajax and request.method == "POST":
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
print('here the data arrives',data)
# here the data arrives {'name': 'Ale', 'friend_id': 22}
Main.objects.create(name=data['name'], friends=data['friend_id'])
return JsonResponse({"instance": data}, status=200)
return JsonResponse({"error": ""}, status=400)
This is the error
raise TypeError("%s() got an unexpected keyword argument '%s'" %
(cls.__name__, kwarg))
TypeError: Main() got an unexpected keyword argument 'Friends'
Any idea or suggestion?
EDIT:
When you are creating the Main object, try making the "friend" attribute an object, like this:
friend = Friend.objects.get(id=data['friend_id'])
Main.objects.create(name=data['name'], friend=friend)
Also, the main issue appears to be you are calling the column "friends" but it should be "friend" when you are creating the Main object.
This:
Main.objects.create(name=data['name'], friends=data['friend_id'])
Should be:
Main.objects.create(name=data['name'], friend=data['friend_id'])
PREVIOUS ANSWER:
Assuming you are using JQuery in the template to send an AJAX request, since you did not specify.
In your urls.py:
...
path('/api/post_friend/', post_friend_api, name="post_friend_api"),
...
In your template :
<script type="text/javascript">
$("#myBurron").click(function(){
var csrfToken = $( "input[name='csrfmiddlewaretoken']"); // assuming this is a form
var friend_name = $("#friend_name").val();
$.ajax({ url: '{% url 'post_friend_api' %}',
type: "POST",
dataType: "json",
data: {'friend':friend_name, 'csrfmiddlewaretoken':csrfToken.val()},
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
In your views.py:
from django.http import JsonResponse
def post_friend_api(request):
data = {}
if request.POST.get('friend', None) is not None:
friend_name = request.POST.get('post_note')
# save the object and indicate success
data['result'] = True
data['message'] = "Friend saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
When you are sending data via POST don't forget to pass along your CSRF token as in the example above. This assumes you have a form on the page you can get it from, otherwise you can use something like this to get it:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
If you don't want to deal with the CSRF token, you can mark the view with the #csrf_exempt decorator and remove the 'csrfmiddlewaretoken' data element from the Ajax call in the template, but it may not be ideal or the most secure. An example of that:
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt()
def post_note_api(request):
...
If you post more details I can update my answer.

AJAX/PYTHON : how to send json value to server

I am a new to Ajax/Python, I don't know how to POST a json value to my python server.
Python code:
#app.route('/ajouterContact', methods = ['POST'])
def ajouterContact():
data = json.loads(request.data)
#nom = request.form['nomContact'];
contact.append(data)
ajouter.make_response(json.dumps(contact), 201)
ajouter.headers['Content-Type'] = 'application/json'
JS code
$('#buttonAjouter').click(function() {
var nom = 'Tom';
var myObj = new Object();
myObj.nom = nom;
var jsonText = JSON.stringify(myObj);
var i = 0;
$.ajax({
url: '/ajouterContact',
data: jsonText,
type: 'POST',
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
I am getting this error on server side :
ValueError: No JSON object could be decoded
If anyone can help me on this..
Thank you!
You need to provide the contentType in your ajax request:
contentType: 'application/json;charset=UTF-8',
Then in your server try to debug something like this:
request.json

can't access json object from python method

I've looked at many answers showing how to access a json in a python method however I can't seem to get mine to work.
Here is my ajax call
var data = {
'customer': customer,
'custID': custID,
'date': date,
'jobNum': jobNum,
'deviceID': deviceID
}
//create customer
if (custID === undefined) {
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
}
else {
//empty
}
and here is my python method:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
response = request.POST
myObject = json.loads(response)
#print myObject["customer"]
test = "hello"
return dict(test=test)
somewhat new to python so pardon my limited understanding. How can I get my json and access the object properties? all i get in my cmd when i tried print was ValueError: No JSON object could be decoded
pyramid has native JSON request support. Set the contentType parameter to application/json to tell the server that you are sending JSON, preferably with a character set (UTF8):
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
and on the server side use request.json_body:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
myObject = request.json_body
print myObject["customer"]
test = "hello"
return dict(test=test)

Categories