Django, Python, Javascript database issue - javascript

I'm trying to create a user system where the user can save a list of their favourite bike racks. I've been using dummy users, but now I'm trying to integrate facebook log to actually create users as you log in. The issue is, even though I'm getting all the right information (console logs have proved this) when I try and add the user to the database through Django it fails. The following is the javascript code that calls django.
function addToFavorites(address, number, l, lon){
alert("Added to favorites!");
console.log("got to addToFavorites "+ user);
$.ajax({
url:'/racks/fave/',
type: "POST",
data: {address: address, number: number, lat:l, lon:lon, user:user,
csrfmiddlewaretoken:'{{ csrf_token }}'
},
The console.logs above are printing the correct thing. This calls the following code:
def add_favorite(request):
if request.method == 'POST':
addUser(request.POST.getlist('user')[0])
u = request.POST.getlist('user')[0]
address = request.POST.getlist('address')[0]
number = request.POST.getlist('number')[0]
lat = request.POST.getlist('lat')[0]
lon = request.POST.getlist('lon')[0]
addFavRack(u, address, number, lat, lon)
which in turn calls addUser:
def addUser(user):
u = UserProfile.objects.get_or_create(user=user)[0]
u.user = user
u.save()
return u

Related

App not redirecting to proper page upon receiving server response

First, I am sorry for the odd name of this thread but I was not sure how to name it.
I am working on a NodeJS app and I seem to have stumble upon a bug I really don't understand.
This is an eLearning app so, at some point, an admin will create quizzes and questions for other users to answer.
The one creating a quiz also has the possibility to duplicate a quiz and edit the title and description of the quiz.
For this I created a route, /duplicatetest.js, that has a GET and a POST method.
The GET method brings the quiz data from the server and sends it to front end for display:
app.get('/duplicatetest/:idTest', isLoggedIn, hasPermision, function(req, res) {
console.log(currentDateTime.getCurrentDate() + " - GET > duplicatetest");
customLogging.customLogging("GET > duplicatetest");
var idTest = req.params.idTest;
getTestToDuplicate.getTestToDuplicate(idTest)
.then(function(result) {
res.render('duplicatetest', {
'test': result
});
});
});
The POST method saves the changes to DB:
app.post('/duplicatetest', isLoggedIn, hasPermision, function(req, res) {
console.log(currentDateTime.getCurrentDate() + " - POST > duplicatetest");
customLogging.customLogging("POST > duplicatetest");
var newTest = req.body.newTest;
saveNewTest.saveNewTest(newTest)
.then(function(result) {
console.log("Sending response now...");
res.send({
"status": 201,
"message": "",
"value": ""
});
});
});
Both seem to be working just fine.
On front-end I have the following JavaScript:
$(document).ready(function()
{
$("#testName").val(test.title);
$("#testDetails").val(test.testDescription);
var url = window.location.pathname;
var idTest = url.split("/");
$("#nextStepTest").click(function()
{
const token = getCookie("u.tkn");
test.token = token;
var title = $("#testName").val();
var details = $("#testDetails").val();
var modifiedTest = {idTest: idTest[2], title: title, description: details, author: token};
var newTest = {newTest: modifiedTest}
$.ajax({
traditional: true,
url: '/duplicatetest',
type: "POST",
contentType: 'application/json',
data: JSON.stringify(newTest),
dataType: 'json',
success: function (response) {
if (response.status == 201) {
window.location = "/tests";
}
},
failure: function (response) {
console.log(response.message[1]);
}
});
});
function getCookie(name)
{
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
});
However, I encounter the following behavior:
I visit /duplicatetest/idTest and make the changes.
Say I have a test with title Test 1 and description Test Description 1.
I change them to Test 1 Duplicate and Test description 1 Duplicate.
On saving, the data is saved in the DB without problems but instead of receiving a response and being redirected to /tests,
the page refreshes, displays the original data (Test 1 and Test Description 1) and the url changes from /duplicatetest/idTest to /duplicatetest/idTest?testName=Test+1+Duplicate (or whatever new name you pick for the new quiz).
On rare occasions however, the redirect works. I am using similar ajax calls for other pages and situations, without any problem.
What I noticed so far is that mostly there is no response from the server in front-end but so far I could not explain why.
What exactly am I doing wrong here and where is that "?testName=Test+1+Duplicate" coming from? I would really appreciate any suggestions since I've been trying to find an explanation for this for some time now...

Stripe API - Workaround for case sensitive email

I'm using the Stripe API and this is using the customer email address in the database however we've just had an issue where someone is signing in to the page using a different case to their sign up and it is not showing them as subscribed.
Obviously I'd like to convert the Stripe emails to all be lowercase but I'm not sure how to do this after getting the email. I am converting the user input to be all lowercase but that just means that if the email in Stripe is not lowercase they are not showing as subscribed.
Thanks in advance
$(document).ready(function() {
var productIDFull = "prod_key00000";
var email = '#User.Identity.Name';
var emailLower = email.toLowerCase();
// check if user has made a purchase in stripe for this product
var hasPurchasedFull = false;
$.ajax({
type: "GET",
url: 'https://api.stripe.com/v1/customers?email=' + emailLower,
headers: {
'authorization': 'Bearer sk_live_0000'
},
success: function(data) {
var isSubscribed = false;
// loop through each customer returned
$.each(data.data,
function(i, customer) {
console.log(customer);
var subscriptions = customer.subscriptions;
console.log(subscriptions);
// loop through each sub
$.each(subscriptions.data,
function(j, subscription) {
console.log(subscription);
var subData = subscription.items.data;
// loop through each plan
$.each(subData,
function(k, planData) {
console.log(planData);
if (planData.plan.product == 'prod_Kc3e_0000' && planData.plan.usage_type == 'licensed') {
isSubscribed = true;
}
});
});
I am converting the user input to be all lowercase but that just means
that if the email in Stripe is not lowercase they are not showing as
subscribed.
This sounds expected based on Stripe's documentation: https://stripe.com/docs/api/customers/list?lang=curl#list_customers-email
The email value is case sensitive, so customer Test#example.com will not be returned if you list customers with email test#example.com
I think a better way to handle this is to store a mapping of Stripe customer IDs and email addresses in an internal database and compare against this database instead of a customer list call.

Sending Array Using Ajax to Django App

So I have some jquery and ajax that collects data from checkbox values. This part is working, I used alert to debug the array to see if the appropriate values are being collected when the checkboxes are ticked.
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type:'POST',
url:'createEvent/',
data:{
name: name,
myCheckboxes: myCheckboxes,
}
});
However on my receiving end I have:
def createEvent(request):
if request.method == "POST":
member = request.POST.getlist('myCheckboxes')
print(member)
Member is an empty array. What am I doing wrong? I can't seem to find the answer.

How to send JSON data created by Python to JavaScript?

I am using Python cherrypy and Jinja to serve my web pages. I have two Python files: Main.py (handle web pages) and search.py (server-side functions).
I create a dynamic dropdown list (using JavaScript) based on a local JSON file called component.json(created by function componentSelectBar inside search.py).
I want to ask how can my JavaScript retrieve JSON data without physically storing the JSON data into my local website root's folder and still fulfil the function of dynamic dropdown list.
The componentSelectBar function inside search.py:
def componentSelectBar(self, brand, category):
args = [brand, category]
self.myCursor.callproc('findComponent', args)
for result in self.myCursor.stored_results():
component = result.fetchall()
if (len(component) == 0):
print "component not found"
return "no"
components = []
for com in component:
t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
components.append(t)
j = json.dumps(components)
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
print "finish component bar"
return "ok"
The selectBar.js:
$.getJSON("static/json/component.json", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
store results from componentSelectBar into database
expose new api to get results from database and return json to browser
demo here:
#cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
...
result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
# here store result into a database, for example, brand_category_search_result
...
#cherrypy.expose
#cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
# load json from that database, here is brand_category_search_result
a_json = loadSearchResult(category, brand)
return a_json
document on CherryPy, hope helps:
Encoding response
In your broswer, you need to GET /getSearchResult for json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
To use that json data directly into javascript you can use
var response = JSON.parse(component);
console.log(component); //prints
OR
You already created json file.If that file is in right format then you can read json data from that file using jQuery jQuery.getJSON() For more: http://api.jquery.com/jQuery.getJSON/
You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.
def componentSelectBar(self, brand, category):
/* Your code goes here */
j = json.dumps(components)
// Code to add a persistent store here
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
// Better to use append mode and append the contents to the file in python
return j //Instead of string ok
#cherrypy.expose
def codeSearch(self):
json_request = cherrypy.request.body.read()
import json # This should go to the top of the file
input_dict = json.loads(json_request)
modelNumber = input_dict.get("modelNumber", "")
category = input_dict.get("category", "")
brand = input_dict.get("brand", "")
/* Your code goes here */
json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
return json_response
Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the componentSelectBar function. That will help you keep the codeSearch function as plain as possible and help in a long run(read maintaining the code).
And I would suggest you to read PEP 8 and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.
EDIT: This is a sample javascript function that will make a post request and get the JSON response:
searchResponse: function(){
$.ajax({
url: 'http://localhost:8080/codeSearch', // Add your URL here
data: {"brand" : "Levis", "category" : "pants"}
async: False,
success: function(search_response) {
response_json = JSON.parse(search_response)
alert(response_json)
// Do what you have to do here;
// In this specific case, you have to generate table or any structure based on the response received
}
})
}

sending notifications to user's friend in facebook using js sdk

I am trying to send notification to user's friend using js sdk on facebook canvas app
but I get this in console
POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140
c.extend.ajax jquery.min.js:140
c.extend.post jquery.min.js:133
makePost ec2-34-41-111-91.ap-southwest-8.compute.amazonaws.com/:69
onclick
I am calling makePost function passing it the friend's profile Id as the argument, this is what I am trying
function makePost(personid){
var accesstoken = FB.getAuthResponse()['accessToken'];
var address = "https://graph.facebook.com/" + personid + "/notifications?";
var tempdata = {};
tempdata['access_token'] = accesstoken;
tempdata['href'] = "";
tempdata['template'] = "You have earned 5 credits, Click here to redeem";
jQuery.post(address, {json: JSON.stringify(tempdata)}, function(data){
console.log(data);
});
}
the person is not receiving the notification.
the problem was that its not the normal access token, here the access token will be a combination of your app id and app secret separated by "|" symbol.
also you need to send the data as an array and not as a json object.
So here is what the working code looks like.
function makePost(personid){
var address = "https://graph.facebook.com/" + personid + "/notifications";
var tempdata = {};
tempdata['access_token'] = appId + "|" + appSecret;
tempdata['href'] = "";
tempdata['template'] = "You have earned 5 credits, Click here to redeem";
jQuery.post(address, tempdata , function(data){
console.log(data);
});
}
PS: I am using Jquery Library to make the post request, So dont forget to include jquery.

Categories

Resources