detail: "CSRF Failed: CSRF token missing or incorrect." - javascript

I have used window.CSRF_TOKEN = "{{ csrf_token }}" inside script tag in restaurant_detail.html where my react page for posting review is rendered. I am getting an error, though. In my onSubmit function i have consoled to check if csrf token is passed or not and yes it is.
my axios code for posting review is
onSubmit(props){
console.log('csrf',CSRF_TOKEN);
axios({
method:'POST',
url:'/api/review/create/',
headers:{
'X-CSRF-Token':CSRF_TOKEN,
//'Access-Control-Allow-Origin':'*',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data:{
review:props.review
}
})
.then(response => {
console.log('success');
})
.catch(error => {
throw("Error: ",error);
});
}
api/Views.py
class ReviewCreateAPIView(CreateAPIView):
queryset = Review.objects.all()
# permisssion_classes = [IsAuthenticated]
def get_serializer_class(self):
model_type = self.request.GET.get('type')
slug = self.request.GET.get('slug')
parent_id = self.request.GET.get('parent_id')
return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user)
serializers.py
def create_review_serializer(model_type='restaurant',slug=None, parent_id=None, reviewer=None):
class ReviewCreateSerializer(ModelSerializer):
class Meta:
model = Review
fields = ('id','review','created',)
def __init__(self, *args, **kwargs):
self.model_type = model_type
self.slug = slug
self.parent_obj = None
if parent_id:
parent_qs = Review.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
self.parent_obj = parent_qs.first()
return super(ReviewCreateSerializer, self).__init__(*args, **kwargs)
def validate(self, data):
model_type = self.model_type
model_qs = ContentType.objects.filter(model=model_type)
if not model_qs.exists() or model_qs.count() != 1:
raise ValidationError('This is not a valid content type')
SomeModel = model_qs.first().model_class()
obj_qs = SomeModel.objects.filter(slug=self.slug) # Restaurant.objects.filter(slug=self.slug)
if not obj_qs.exists() or obj_qs.count() != 1:
raise ValidationError('This is not a slug for this content type')
return data
def create(self, validated_data):
review = validated_data.get('review')
print('review',review)
if reviewer:
main_reviewer = reviewer
else:
main_reviewer = User.objects.all().first()
model_type = self.model_type
slug = self.slug
parent_obj = self.parent_obj
review = Review.objects.create_for_model_type(model_type, slug, review, main_reviewer, parent_obj=parent_obj)
return review
return ReviewCreateSerializer
urls.py
url(r'^create/$', ReviewCreateAPIView.as_view(), name="reviewcreateapiview"),
restaurant_detail.html
<div id="app"></div>
<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
How can i resolve this?

You have done a simple error. There is a typo. Do replace
'X-CSRF-Token'
to
'X-CSRFToken'
if you have code correctly, then it should post your data.

I'm not familiar with axios,but I solved a similar problem use the blow code with JQuery:
$.ajaxSetup({
data : {
csrfmiddlewaretoken : '{{ csrf_token }}'
},
});

you have to set the header in ajax call with cookie values.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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 = jQuery.trim(cookies[i]);
// 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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});

Related

Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django)

I'm using DestroyAPIView with Javascript to delete the cart item in Django
While clicking on delete button it shows the following error on chrome console:
jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
destoryCart # (index):46
onclick # (index):1
(index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
and in vs code terminal showing:
Not Found: /showdata/2342;
and all my code goes here:
views.py
class CartDestroyAPIView(DestroyAPIView): # DeleteView
permission_classes = [IsAuthenticated] # Or anything else you want
authentication_classes = [SessionAuthentication] # Or anything else you want
serializer_class = productserializers
queryset = Cart.objects.all()
index.html
<script>
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:8000/showdata ',
dataType: 'JSON',
success: function(data){
for (var i = 0; i < data.length; i++)
{
var row =
$('<tr><td style="font-style:bold">'
+data[i].product.name+'</td><td style="font-style:bold">'
+data[i].product.price+'</td><td><a href='
+data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>');
$("#tableProduct").append(row);
}
}
});
});
const destoryCart = (id) => {
let url = `http://127.0.0.1:8000/showdata/${id};`
$.ajax({
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}");
},
url: url,
type: 'DELETE',
success: (data) => {
console.log("deleted!");
},
error: (err) => {
console.log(err);
}
});
};
</script>
urls.py
path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'),
WHAT IS WRONG GOING WITH THIS CODE.
Change your URL in ajax call you have to put this URL in side your destoryCart()
let url = `http://127.0.0.1:8000/cart_destroy/${id};`
instead of this URL http://127.0.0.1:8000/showdata/${id};
UPDATE
get csrf_token like this i don't know if there is another way but as per official doc.
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const 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;
}
const csrftoken = getCookie('csrftoken');
And you ajax call
const destoryCart = (id) => {
$.ajax({
type: 'POST',
url: "{% url 'cart_destroy' %}",
data: {
'product_id': id,
'csrfmiddlewaretoken': csrftoken,
},
success: function(success) {
console.log('success : '+success.responseText)
},
error: function(error) {
console.log('error : '+error.responseText)
},
});
}
and you have to update your URL also like this
path('cart_destroy/', views.CartDestroyView, name ='cart_destroy'),
add this in your views.py
def CartDestroyView(request):
if request.method == "POST":
product_id = request.POST['product_id']
Cart.objects.filter(id=product_id).delete()
return HttpResponse({'Success':"Deleted Successfully."})

update function failing, create & delete working

I can create, delete and display all but the update function will not work and does nothing. When I look the error in the console log it points to
jquery.min.js:2 PUT http://localhost:5000/shop/9 400 (BAD REQUEST)
send # jquery.min.js:2
ajax # jquery.min.js:2
updateServer # index.html:133
doUpdate # index.html:129
onclick # index.html:35
index.html:147
I cant see where I am going wrong. Am I missing something or is it within the update server code? This is the html code. A lot of the code for the update server is taken from other places within the html which works fine.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title> View Shopping List</title>
</head>
<body>
<h1>Shop</h1>
<div id="create-update" style="display:none">
<h2>create-edit</h2>
<table id="createUpdateForm">
<tr>
<td>ID</td>
<td><input type="hidden" name="ID" id="idInput"></td>
</tr>
<tr>
<td>Dept</td>
<td><input type="text" name="Dept"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name"></td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="Amount"></td>
</tr>
<tr>
<td></td><td>
<button id="create-button" onclick="doCreate()">Create</button>
<button id="update-button" onclick="doUpdate()">update</button>
</td>
</tr>
</table>
</div>
<div id="display">
<h2>Shop</h2>
<button onClick="showCreate()">Create</button>
<table id="shopTable" class="table">
<tr>
<th>ID</th><th>Dept</th><th>Name</th><th>Amount</th><th></th><th></th>
</tr>
</table>
</div>
JS:
function showCreate() {
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "none"
document.getElementById('create-button').style.display = "block"
document.getElementById('create-update').style.display = "block"
}
function showUpdate(thisElem) {
var rowElement = thisElem.parentNode.parentNode;
shop = readShopFromRow(rowElement)
populateForm(shop)
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "block"
document.getElementById('create-button').style.display = "none"
document.getElementById('create-update').style.display = "block"
}
function readShopFromRow(rowElement) {
shop = {}
shop.ID = rowElement.getAttribute("ID");
shop.Dept = rowElement.cells[1].firstChild.textContent
shop.Name = rowElement.cells[2].firstChild.textContent
shop.Amount = rowElement.cells[3].firstChild.textContent
return shop
}
function populateForm(shop) {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = shop.ID
form.querySelector('input[name="ID"]').disabled = true
form.querySelector('input[name="Dept"]').value = shop.Dept
form.querySelector('input[name="Name"]').value = shop.Name
form.querySelector('input[name="Amount"]').value = shop.Amount
}
function clearForm() {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = ''
form.querySelector('input[name="ID"]').disabled = false
form.querySelector('input[name="Dept"]').value = ''
form.querySelector('input[name="Name"]').value = ''
form.querySelector('input[name="Amount"]').value = ''
}
function doCreate() {
console.log("in doCreate")
shop = getShopFromForm()
console.log(shop)
$.ajax({
url: "/shop",
data: JSON.stringify(shop),
method: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
addShopToTable(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doUpdate() {
shop = getShopFromForm()
updateServer(shop)
}
function updateServer(shop) {
$.ajax({
url: "/shop/" + shop.ID,
data: JSON.stringify(shop),
method: "PUT",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
updateTableRow(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doDelete(thisElem) {
var tableElement = document.getElementById('shopTable');
var rowElement = thisElem.parentNode.parentNode;
var index = rowElement.rowIndex;
ID = rowElement.getAttribute("id");
$.ajax({
url: "/shop/" + ID,
method: "DELETE",
dateType: "JSON",
success: function(result) {
tableElement.deleteRow(index);
},
error: function(xhr, status, error) {
console.log(error)
}
})
}
function updateTableRow(shop) {
rowElement = document.getElementById(shop.ID)
rowElement.cells[1].firstChild.textContent = shop.Dept
rowElement.cells[2].firstChild.textContent = shop.Name
rowElement.cells[3].firstChild.textContent = shop.Amount
//console.log("updating table")
}
function getShopFromForm() {
var form = document.getElementById('createUpdateForm')
var shop = {}
shop.ID = form.querySelector('input[name="ID"]').value
shop.Dept = form.querySelector('input[name="Dept"]').value
shop.Name = form.querySelector('input[name="Name"]').value
shop.Amount = form.querySelector('input[name="Amount"]').value
//console.log(shop)
return shop
}
function showDisplay() {
document.getElementById('display').style.display = "block"
document.getElementById('create-update').style.display = "none"
}
function populateTable() {
//ajax getAll
$.ajax({
url: 'http://127.0.0.1:5000/shop',
method: 'GET',
datatype: 'JSON',
success: function(results) {
for (shop of results) {
addShopToTable(shop)
}
},
error: function(xhr, status, error) {
console.log("error " + error + " code:" + status)
}
})
}
function addShopToTable(shop) {
//console.log("working so far")
tableElem = document.getElementById("shopTable")
rowElem = tableElem.insertRow(-1)
rowElem.setAttribute("ID", shop.ID)
cell1 = rowElem.insertCell(0)
cell1.innerHTML = shop.ID
cell2 = rowElem.insertCell(1)
cell2.innerHTML = shop.Dept
cell3 = rowElem.insertCell(2)
cell3.innerHTML = shop.Name
cell4 = rowElem.insertCell(3)
cell4.innerHTML = shop.Amount
cell5 = rowElem.insertCell(4)
cell5.innerHTML = '<button onclick="showUpdate(this)">Update</button>'
cell6 = rowElem.insertCell(5)
cell6.innerHTML = '<button onclick="doDelete(this)">delete</button>'
}
populateTable()
Server API
from flask import Flask, jsonify, request, abort, make_response, url_for, render_template, redirect #https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates Render template takes template and returns actual values
from flask_cors import CORS
from ShoppingDAO import ShoppingDAO
#from userinput import userinput
app = Flask(__name__,
static_url_path='',
static_folder='staticpages')
CORS (app)
#app.route('/')
def hello_world():
return 'Hello World'
# curl http://127.0.0.1:5000/
#app.route('/shop')
def getAllShop():
return jsonify(ShoppingDAO.getAllShop())
# curl http://127.0.0.1:5000/shop
# find By dept
#app.route('/shop/<string:Dept>', methods =['GET'])
def findShopByDept(Dept):
return jsonify(ShoppingDAO.findShopByDept(Dept))
# curl http://127.0.0.1:5000/shop/Spud
# find By ID
##app.route('/shop/<int:ID>')
#def findShopByID(ID):
# return jsonify(ShoppingDAO.findShopByID(ID))
# curl http://127.0.0.1:5000/shop/1
#app.route('/shop/<int:ID>', methods =['GET'])
def findShopByID(ID):
foundShop = ShoppingDAO.findShopByID(ID)
return jsonify(foundShop)
# Create
#app.route('/shop', methods=['POST'])
def createShop():
if not request.json:
abort(400)
if not 'ID' in request.json:
abort(400)
Shop={
"Dept": request.json['Dept'],
"Name":request.json['Name'],
"Amount":request.json['Amount']
}
values = (Shop['Dept'], Shop['Name'], Shop['Amount'])
newId = ShoppingDAO.createShop(values)
Shop['ID'] = newId
return jsonify(Shop)
# curl -X POST -d "{\"ID\":1, \"Dept\":\"Fresh\", \"Name\":\"Test\", \"Amount\": 5}" -H Content-Type:application/json http://127.0.0.1:5000/shop
#app.route('/shop/<int:ID>', methods=['PUT'])
def updateShop(ID):
foundShop = ShoppingDAO.findShopByID(ID)
if not foundShop:
abort(404)
if not request.json:
abort(400)
reqJson = request.json
if 'Amount' in reqJson and type(reqJson['Amount']) is not int:
abort(400)
if 'Dept' in reqJson:
foundShop['Dept'] = reqJson['Dept']
if 'Name' in reqJson:
foundShop['Name'] = reqJson['Name']
if 'Amount' in reqJson:
foundShop['Amount'] = reqJson['Amount']
values = (foundShop['Dept'],foundShop['Name'],foundShop['Amount'],foundShop['ID'])
ShoppingDAO.updateShop(values)
return jsonify(foundShop)
# curl -X PUT -d "{\"Dept\":\"Monday\", \"Name\":\"Mondy\", \"Amount\": 50}" -H Content-Type:application/json http://127.0.0.1:5000/shop/3
# Delete
#app.route('/shop/<int:ID>' , methods=['DELETE'])
def deleteShop(ID):
ShoppingDAO.deleteShop(ID)
return jsonify({"done":True})
# curl -X DELETE http://127.0.0.1:5000/shop/2
if __name__ == '__main__' :
app.run(debug= True)
The value property is a string, so the test type(reqJson['Amount']) is not int is succeeding and you're reporting an error.
Convert the amount to an integer when creating the JSON:
shop.Amount = parseInt(form.querySelector('input[name="Amount"]').value)

Display message from Lambda via Javascript after successful form submit

I'm using this code to add a contact form to my Serverless website (hosted on S3). When an email is successfully sent, the Lambda instance returns the message "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>". I want to display that message to the user who submitted the form but I can't figure out how to do so. Currently, my javascript displays a hard-coded message based on the response code from the AWS API Gateway. But I don't want to include the download url in the javascript because I don't want users to be able to see the download without first signing up via the form.
Is there a way to grab the string returned by the Lambda instance and pass it back in the response body and then display that message to the user via javascript?
My current jQuery javascript for the form:
! function($) {
"use strict";
$("form", ".contact-form ").submit(function(t) {
t.preventDefault();
var r = !0,
s = this,
e = $(s).siblings(".contact-form-result"),
o;
// Escape if the honeypot has been filled
if (!!$("#whatname").val()) return;
if ($(s).find(":required").each(function() {
$(this).css("border-color", ""), $.trim($(this).val()) || ($(this).css("border-color", "red"), r = !1);
var t = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
"email" != $(this).attr("type") || t.test($.trim($(this).val())) || ($(this).css("border-color", "red"), r = !1)
}).keyup(function() {
$(this).css("border-color", "")
}).change(function() {
$(this).css("border-color", "")
}), r) {
//var c = $(this).serialize();
var firstname = $("#name-input").val();
var lastname = $("#lastname-input").val();
var mobile = $("#mobile-input").val();
var email = $("#email-input").val();
var message = $("#message-input").val();
var data = {
firstname : firstname,
lastname : lastname,
mobile : mobile,
email : email,
message : message }
$.ajax({
url: "PATH-TO-AMAZON-API",
type: "post",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
beforeSend: function(data) {
$('#submit-mail').attr('disabled', true);
//$('#status').html('<i class="fa fa-refresh fa-spin"></i> Sending Mail...').show();
o = '<p class="form-message form-success">Sending...</p>';
e.removeClass("hidden").html(o)
},
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">Thank you for your message!</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},
error: function (jqXHR, textStatus, errorThrown) {
// show an error message
//alert("UnSuccessfull");
o = '<p class="form-message form-error">Sorry, there was an error. Please try again later.</p>';
e.removeClass("hidden").html(o)
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
}
});
}
})
}(jQuery);
And my Python Lambda function (using an API, SES and Dynamo [not currently using Dynamo]):
import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import uuid
import decimal
client = boto3.client('ses')
sender = os.environ['SENDER_EMAIL']
subject = os.environ['EMAIL_SUBJECT']
configset = os.environ['CONFIG_SET']
charset = 'UTF-8'
dynamodb = boto3.resource('dynamodb')
recipient = 'example#email.com'
def sendMail(event, context):
print(event)
#Send mail for contact form
try:
data = event['body']
content = 'Message from ' + data['firstname'] + ' ' + data['lastname'] + ',<br>Phone: ' + data['mobile'] + ',<br>Message Contents: ' + data['message']
#saveToDynamoDB(data)
response = sendMailToUser(data, content)
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message Id:"),
print(response['MessageId'])
return "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>"
def list(event, context):
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
# fetch all records from database
result = table.scan()
#return response
return {
"statusCode": 200,
"body": result['Items']
}
def saveToDynamoDB(data):
timestamp = int(time.time() * 1000)
# Insert details into DynamoDB Table
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
item = {
'id': str(uuid.uuid1()),
'firstname': data['firstname'],
'lastname': data['lastname'],
'email': data['email'],
'message': data['message'],
'createdAt': timestamp,
'updatedAt': timestamp
}
table.put_item(Item=item)
return
def sendMailToUser(data, content):
# Send Email using SES
return client.send_email(
Source=sender,
ReplyToAddresses=[ data['email'] ],
Destination={
'ToAddresses': [
recipient,
],
},
Message={
'Subject': {
'Charset': charset,
'Data': subject
},
'Body': {
'Html': {
'Charset': charset,
'Data': content
},
'Text': {
'Charset': charset,
'Data': content
}
}
}
)
Thanks for your help!
Well, that was easy...after all the searching online for days trying to figure this out. Turns out the message is right there in success: function (data) so I all I have to do is return the data variable in my javascript. So it would look like this:
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">' + data + '</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},

Jquery Post two Array AngularJS

Im trying to send two Arrays on my AngularJS app but i get "404 URL Not Found". Is this ok? What am i missing?
My AngularJS code:
$scope.Guardar = function () {
if (confirm('¿Está seguro de guardar los datos?')) {
$("#btnGuardar").prop('disabled', 'disabled');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
var nombreRegla = $("#lblNombreRegla").val();
var localesEnGrilla = $("#localesGrilla").val();//array1
var articulosEnGrilla = $("#articulosGrilla").val();//array2
$http({
method: 'POST',
url: baseURL + 'Configuracion/CrearRegla/',
data: { "Nombre": nombreRegla, "Locales": localesEnGrilla, "Articulos": articulosEnGrilla, "CurrentUser": userName }
}).success(function (result) {
if (result != null) {
$("#btnGuardar").prop('disabled', '');
$scope.MostrarMensajeOk = false;
$scope.MostrarMensajeError = false;
$scope.volver();
}
});
};
};
And my Controller :
public void CrearRegla(string Nombre, string Locales, string Articulos, string CurrentUser)
{
//staff
}
The error that give me is "404 not found URL"
"404 URL Not Found" means that's url not valid.
Make sure that's baseURL end with / and for 'Configuracion/CrearRegla/' try without / like this 'Configuracion/CrearRegla'

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