I am trying to send data from javascript/ajax (selected regions and city information) to flask and then return processed data back to javascript. The 'var data' look like {"region1":"Asia","city1":"Taipei","region2":"S America"} on console.log.
I get error within ajax.
javascript:
$(function() {
$('#button').on('click', function() {
var data = {'region1': $('select[name=slct1]').val(),
'city1': $('select[name=slct2]').val(),
'region2': $('select[name=slct3]').val()};
console.log(data);
$.ajax({
url: '/receive',
type: 'post',
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
data: data,
success: function(data2){
alert('success');},
error: function(){alert('failure');}
});
});
});
Flask: Temp1 and other variables (np array) for City1 are extracted from pandas db.
#app.route('/receive', methods=['POST', 'GET'])
def receive():
if request.method == 'POST':
data = request.form['data']
City1 = data['city1']
Temp1 = some_function(City1) # np array
return jsonify({'Temp1': list(Temp1)})
I think the data received in Flask should be parsed like this:
if request.method == 'POST':
data = request.get_data()
data = json.loads(data)
City1 = data['city1']
Related
I am trying to submit localstorage data via a POST request using the below jquery ajax method. How should I write my view so I can Parse my JSON object and get a hold of "product_id" to execute the below command in my Django view. Please see a copy of my view below.
Trying since one week, but I failed to fix the issue
Is there any better way of achieving this ?
My Ajax:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: data_url,
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (result) {
console.log("Success")
},
});
});
and My Views:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
return render (request, './compare.html', context)
Actually my localStorage is on following format:
("comparisionItems"({ images: products, itemIds: itemIds }));
Can you please help me how can I pass itemIds to views and return item from views for the itemsIds?
Console log for console.log(compareObj)
https://imgur.com/MxdZrgy
since .is_ajax() is deprecated you cant use that, but you can check if the request is an XMLHttpRequest like below.
from django.shortcuts import get_object_or_404
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = request.POST.get('compare_id')
product = get_object_or_404(Products, product_id=id)
context={ 'product':product,}
return render (request, './ecommerce/compare.html', context)
note; the get_object_or_404 is just a shortcut for:
try:
product = Products.objects.get(product_id=id)
except:
raise Http404
I'm trying to send an array to my python function inside views.py but I can't. It always crash with a keyError because is not recognising the data from js.
Code:
Python function in views.py:
def cargar_datos_csv(request):
if request.method == 'POST':
filtros = request.POST['node']
print(filtros)
ctx = {'A':filtros}
return JsonResponse(ctx)
JS
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var frutas = ['Manzana', 'Banana'];
$.ajax({
url: '/../../data_bbdd/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'node': frutas,
},
dataType: "json",
cache: true,
success: function(response) {
coords = JSON.stringify(response.A);
alert(coords);
}
});
How can I send an array to my python function?
Thank you very much.
Because node is a list it will be posted as node[] by JQuery so you can get it using request.POST['node[]'] or request.POST.getlist('node[]')
More informations on why this is the behavior of JQuery on this stackoverflow's answer :django - getlist()
I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page.
Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file.
However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data.
Views.py
i=0
uploaded_file = None
def home(request):
if (request.method == 'POST'):
file_form = UploadFileForm(request.POST, request.FILES)
if file_form.is_valid():
global uploaded_file
uploaded_file = request.FILES['file']
print(uploaded_file)
else:
file_form = UploadFileForm()
return render(request, 'personal/home.html', {'form': file_form})
def handle(request):
# TODO make ajax wait for a response from 'home'
# so I don't have to wait for 1 second
time.sleep(1)
data = {}
data['Name'] = fileName(uploaded_file)
if(request.is_ajax()):
print(data) # prints succesfully
return HttpResponse(json.dumps(data),
content_type="application/json")
home.html
<script type = "text/javascript" language = "javascript">
function post_tables(data) {
alert(data)
}
$(document).ready(function(post_tables) {
$("#upload").click(function(event){
$.ajax( {
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "get",
url:'/handler',
success: function(data) {
console.log("over here")
post_tables(data)
},
error: function(data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
});
</script>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler', views.handle, name='handle'),
]
I explained the whole process ajax django to you. Perhaps your problem will be solved. good luck.
views.py
def handle(request):
if request.method == 'POST':
data = request.POST
field_example = data.get('field_example')
return JsonResponse(data)
else:
data = request.GET
field_example = data.get('field_example')
return JsonResponse(data)
home.html
<form id="upload">
{% csrf_token %}
<input type="text" name=field_example>
.
.
.
</form>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler/', views.handle, name='handle'),
]
js code in home.html:
$("#upload").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "{% url 'handle' %}",
type: 'GET',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("over here")
post_tables(data)
},
error: function (data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
I'm trying to display the error messages that I provided on my forms, but it only display the id name instead of error message.
Here's my code
Form.py
class SecurityCode(forms.Form):
sCode = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(id="scode", name="scode", required=True, size=25, placeholder=" Security Code")), error_messages={ 'invalid': "This value must contain only letters, numbers and underscores." })
Views.py
def security(request):
if request.method == 'POST':
securityField = SecurityCode(request.POST)
if taxpayerField.is_valid():
return HttpResponse("success")
else:
return HttpResponse(taxpayerField.errors)
Note: I'm trying to get the error message in this views not on my html because I'm trying to alert that on my javascript. Also this is just my sample code not the original one.
You can try this:
views.py:
from django.http import JsonResponse
def security(request):
form = SecurityCode(request.POST)
if not form.is_valid():
return JsonResponse({
'success': False,
'err_code': 'invalid_form',
'err_msg': form.errors,
})
#[...] Actions if form is valid ...
return render(request, 'template.html')
javascript code:
def submit_form(){
var data = {
field1: '...',
field2: '...',
csrfmiddlewaretoken: 'csrftoken',
};
$.ajax({
url: '/submit/form/',
method: 'POST',
data: data,
dataType: 'json',
success: function (data){
if (data.success){
// Actions ...
}
else if (data.err_code === 'invalid_form'){
for(var key in data.err_msg){
console.log('[error] for ' + key + ': ' + data.err_msg[key][0]);
}
}
},
});
}
I use console.log to illustrate the recovery of the error message for each field.
I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.