How to Parse LocalStorage JSON object in Django View from Ajax? - javascript

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

Related

Using Ajax to passing multiple value and fetching data in view to export it in excel in Django

View.py
def export(request):
if request.is_ajax():
ourid = request.GET.getlist("terid")
Case_Detail = Case_Info_Resource()
for i in ourid:
print(i)
queryset = Case_Info.objects.filter(id=i)
dataset = Case_Detail.export(queryset)
response = HttpResponse(
dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
print("breakpoint")
return response
Ajax Script
<script>
$(document).ready(function () {
$('#Download').click(function () {
var list = [];
$("input:checkbox[name='checkbox']:checked").each(function () {
list.push($(this).val());
});
$.ajax({
url: '/Account_Manager/Download/',
type: 'GET',
data: { 'terid': list },
traditional: true,
dataType: 'html',
success: function () {
alert("The best cricketers are: " + list.join(", "));
}
});
});
});
</script>
Error:
The view Apps.views.export didn't return an HttpResponse object. It returned None instead.
So, Ajax wants us to return the value in HttpResponse but I need to pass the response normally in order to download the excel which I am creating. I think I checked all the possible answers and struggling with it from the last 3 days. Thank you in advance for any help, suggestions, or edit.

django run custom views class method with one url

I'm new to django. I want to manage my database with custom methods inside the views file. for example, I have this code I would like to run with javascript - I wrote this code:
Js:
$.ajax({
type: 'POST',
url: '/ClassManager/',
data: {
data: data,
csrfmiddlewaretoken: csrftoken,
},
success: function() {
alert("IT WORKED")
},
error: function() {
alert('error');
}
})
views.py
def expfunc():
if request.method == 'POST':
user = User.objects.get(pk=1)
addlst = List(content = "list content", creator = user)
addlst.save()
urls.py
urlpatterns = [
path('ClassManager/', views.expfunc),
]
now, the problem is, that for every new function that I want to create in the views.py, I need to add another line in the urls.py.
my question is - if there a way to create a class with all of the custom methods, and access them with one url and different data?
for example:
Js:
$.ajax({
type: 'POST',
url: '/ClassManager/functionone()',
data: {
data: data
csrfmiddlewaretoken: csrftoken,
},
success: function() {
alert("IT WORKED")
},
error: function() {
alert('error');
}
})
views.py
class DatabaseManager():
def functionone(): # add new list
if request.method == 'POST':
user = User.objects.get(pk=1)
addlst = List(content = "list content", creator = user)
addlst.save()
def functwo(): # update username
if request.method == 'POST':
user = User.objects.get(pk=1)
user.id = 9
user.save()
def functhree(): # update list content
if request.method == 'POST':
user = User.objects.get(pk=1)
mylist = List.objects.get(pk=1)
mylist.content = "updated list content"
mylist.save()
urls.py
urlpatterns = [
path('ClassManager/functionone()', views.DatabaseManager.functionone),
]
I came from asp.net background where I wrote classes with functions that ran queries and that it how I managed my database, so can I do the same here?
Thanks In Advance!
You can use Class Based View to implement your views as Python objects instead of functions, but you can't call a class function with Ajax.

How to handle request json data in flask

I would like to send json formatted data from my html page to a url on the click of a button, but currently the data is not getting updated to the url. I've included here a small subset of the data i'm trying to post. The GET method works fine for posting initial output to the url. The result of the ajax request is the alerted error output. How can I use POST to successfully update the output to the url?
The html:
<button type="submit" class="btn-sm btn-success btn-space" id ="commitButton" name="commitButton" value="enter">Commit</button>
Javascript:
<script>
document.getElementById('commitButton').onclick = function() {
$.ajax({
url: "/processjson",
type:'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
"dataType": "json",
"data": {"schema": {"fields":[{"name":"index","type":"integer"},{"name":"OB_TIME","type":"datetime"},{"name":"LATITUDE","type":"number"},{"name":"LONGITUDE","type":"number"}]}, "data": [{"index":0,"OB_TIME":"2015-09-03T00:00:00.000Z","LATITUDE":21.9,"LONGITUDE":-152.0}]},
"contentType": "application/json",
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
})
};
</script>
Flask:
#app.route('/processjson', methods=['GET','POST'])
#login_required
def processjson():
if request.method == 'GET':
return jsonify({'result':'Test'})
# getting the table data when the commit button is pressed
if request.method == 'POST':
# gets jsonified data and convert it to a python data structure (dictionaries)
data = request.get_json()
fields = data['schema']['fields']
tableData = data['schema']['data']
return jsonify({'result':'Success!','tableData' : tableData})
Place the json data inside the request body.
You can access the request body with request.form.get('data') to get a json string. This can be load to a dict using json.load(json_str).
request.get_json() parse form data as json, but this would work if you are submitting as form data. Looking at the JS snippet, it looks like you are not submitting it as form data (you are making an ajax call), so your data will be available in the property request.json
you can use like this : request.json

Why an ajax call doesn't give .is_ajax()=True?

My template.html:
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My javascript.js:
function save_post(event, action) {
event.preventDefault();#new line
var tag_string=document.getElementById('id_tags').value;
if (action=='publish' || action=='draft') {
var url_post='/blog/post/new/'
} else {
var url_post='/blog/post_edit/'
};
$.ajax({type: 'POST',
url: url_post,
data: {
tagstring: tag_string,
action: action
},
success: function (lista) {
//code
}
});
};
My views.py:
#staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
My url.py:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" and this works, but request.is_ajax() gives False.
For call post_edit (probabily) I need the id of the post. Where can I get it?
Should I pass it to save_post() from the template?
Edit: ignore these lines below
Also should I use preventDefault() somewhere?
Thank you
Edit: now I use preventDefault() but it gives this error:
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
and ajax dosn't call the view. Edit: I solved this problem, but I continue tomorrow :)
Your Ajax code some problems and view is correct
I have attached my Code attached Image and code
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})

django ajax call return 403 bad request

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.

Categories