How to use AJAX with Google App Engine (Python) - javascript

I am completely novice at AJAX. I am familiar with HTML/CSS, jQuery and beginner at GAE and Python.
In an effort to understand how AJAX works, I would like to know how AJAX might be used (actual code) in this example below. Let's use a reddit-like example where vote ups/downs are ajaxified:
Here is the Story Kind:
class Story(ndb.Model):
title = ndb.StringProperty(required = True)
vote_count = ndb.IntegerProperty(default = 0)
The HTML would look like this:
<h2>{{story.title}}</h2>
<div>
{{story.vote_count}} | Vote Up Story
</div>
How does AJAX fit inside here?

Ok Sir here we go... A simple app with one story and infinite votes... ;-)
app.yaml
application: anotherappname
version: 1
runtime: python27
api_version: 1
threadsafe: true
default_expiration: "0d 0h 5m"
libraries:
- name: jinja2
version: latest
- name: webapp2
version: latest
handlers:
- url: .*
script: main.app
main.py
import logging
from controllers import server
from config import config
import webapp2
app = webapp2.WSGIApplication([
# Essential handlers
('/', server.RootPage),
('/vote/', server.VoteHandler)
],debug=True, config=config.config)
# Extra Hanlder like 404 500 etc
def handle_404(request, response, exception):
logging.exception(exception)
response.write('Oops! Naughty Mr. Jiggles (This is a 404)')
response.set_status(404)
app.error_handlers[404] = handle_404
models/story.py
from google.appengine.ext import ndb
class Story(ndb.Model):
title = ndb.StringProperty(required=True)
vote_count = ndb.IntegerProperty(default = 0)
controllers/server.py
import os
import re
import logging
import config
import json
import webapp2
import jinja2
from google.appengine.ext import ndb
from models.story import Story
class RootPage(webapp2.RequestHandler):
def get(self):
story = Story.get_or_insert('Some id or so', title='A voting story again...')
jinja_environment = self.jinja_environment
template = jinja_environment.get_template("/index.html")
self.response.out.write(template.render({'story': story}))
#property
def jinja_environment(self):
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__),
'../views'
))
)
return jinja_environment
class VoteHandler(webapp2.RequestHandler):
def post(self):
logging.info(self.request.body)
data = json.loads(self.request.body)
story = ndb.Key(Story, data['storyKey']).get()
story.vote_count += 1
story.put()
self.response.out.write(json.dumps(({'story': story.to_dict()})))
and finally
views/index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<h2>{{story.title}}</h2>
<div>
<span class="voteCount">{{story.vote_count}}</span> | <a href="javascript:VoteUp('{{story.key.id()}}');" >Vote Up Story</a>
</div>
<script>
function VoteUp(storyKey){
$.ajax({
type: "POST",
url: "/vote/",
dataType: 'json',
data: JSON.stringify({ "storyKey": storyKey})
})
.done(function( data ) { // check why I use done
alert( "Vote Cast!!! Count is : " + data['story']['vote_count'] );
$('.voteCount').text(data['story']['vote_count']);
});
};
</script>
</body>
</html>
Assemble, read it's simple enough and run. If you need a working git example just comment.
githublink (as from comments)

Here is a little prototype web app on GitHub to test how to handle error messages in HTML form submissions with AJAX, Python and Google App Engine. It will give a starting point to see how these three pieces of technology mesh together. You can test this "app" on https://ajax-prototype.appspot.com/
Here is how it works on the client-side:
This htlm form submission is used:
<form method="post" action="javascript:ajaxScript();">
<label>Please pick a name</label>
<input id="input" type="text">
<input type="submit">
<div id="error" style="color:red"></div>
It will trigger the JavaScript function ajaxScript:
function ajaxScript() {
var input = $("#input").val();
$.ajax({
type: "POST",
url: "/",
data: JSON.stringify({
"name": input
}),
dataType: "json"
})
.done(function(jsonResponse) {
$("#error").html(jsonResponse.message);
});
}
The jQuery .ajax() method handles the request while the .done() method will eventually handle the response that it gets from the server.
On the server-side:
The main.py file handles the server side of the business using our handler class AjaxHandler, which inherits from the GAE builtin class webapp2.RequestHandler
Within this class, the post method handles the AJAX request:
def post(self):
data = json.loads(self.request.body)
username = data["name"]
if not re.match(r"^[a-zA-Z0-9_-]{3,20}$", username):
if len(username) < 3:
message = "Your name must be at least 3 characters long."
else:
message = "Allowed characters are \
a-z, A-Z, 0-9, underscores \
and hyphens."
else:
message = "Congrats!"
self.response.write(json.dumps({"message": message}))
Basically, the handy json module provides the two key Python ingredients
json.loads handles the data that the browser sends to the server.
json.dumps handles the data sent by the server in response to the browser's request.
The self.request.body argument of json.loads is the only less common piece of GAE that is used in the process, as it is specific to the task. As its name suggests, it gets the body from the Ajax request sent by the client.

Related

use json list element inside a jinja statement using js or jquery

this is my code:
$("select").change(function(){
$.post("/sort", {sort:$(this).val()}, function(table_data)
{
for (let i in table_data)
{
var tr = $("<tr/>");
var filename = table_data[i].filename;
var size = table_data[i].size;
var uploaded = table_data[i].upload_time;
tr.append("<td>"+filename+"</td>");
tr.append("<td>"+size+"</td>");
tr.append("<td>"+uploaded+"</td>");
**tr.append("<td>"+"<a href='{{url_for('.download', filename=***filename***)}}'>"+'Download'+"</a>"+"</td>")**;
tr.appendTo(table);
}
Interestingly the jinja statement inside the js statement works, the browser directs to that path, but the filename remains None, because the server, which is using python flask, cannot resolve the value sent from here which is a js variable. Table_data is a json that was returned from the server using jsonify in response to an ajax call. My question is if there's any way to use that 'filename' js variable inside that jinja statement, or perhaps convert it to a jinja variable. Thanks.
As I wrote in my comment, it is only possible to pass variables from Jinja to JavaScript when the page is served. This time has already passed during the AJAX request.
I think the best solution is to construct the url with url_for on the server and transfer it via JSON with the record. So your requirements should be met.
I wrote you a small example, which is based on your question.
All folders in the application's static folder are listed and made available to the user for selection. If he selects a directory, file information and the download URL are queried via Ajax. The information is then displayed in a table.
Flask (app.py)
import os
from datetime import datetime
from flask import Flask
from flask import (
jsonify,
render_template,
request,
send_from_directory,
url_for
)
app = Flask(__name__)
#app.route('/')
def index():
# List all folders in the static folder.
folders = [file \
for file in os.listdir(app.static_folder) \
if os.path.isdir(os.path.join(app.static_folder, file))
]
return render_template('index.html', **locals())
#app.route('/stats', methods=['POST'])
def stats():
# Return stats of all files in the selected folder.
if 'target' in request.form:
data = []
target = request.form['target']
try:
for filename in os.listdir(os.path.join(app.static_folder, target)):
filepath = os.path.join(app.static_folder, target, filename)
data.append(
{
'filename': filename,
'filesize': os.path.getsize(filepath),
'filetime': datetime.fromtimestamp(os.path.getmtime(filepath)).isoformat(),
'filedest': url_for('.download', filename=os.path.join(target, filename))
}
)
return jsonify(data)
except OSError: pass
return '', 400
#app.route('/download/<path:filename>')
def download(filename):
return send_from_directory(app.static_folder, filename)
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<select name="target">
<option disabled selected value>-- select an option --</option>
{% for folder in folders -%}
<option value="{{folder}}">{{folder}}</option>
{% endfor -%}
</select>
<table id="my-table" style="width: 100%"></table>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script type="text/javascript">
((uri) => {
$(document).ready(function() {
$('select[name="target"]').change(function(evt) {
$('table#my-table').empty();
$.post(uri, { target: $(this).val() })
.done(function(data) {
data.forEach(info => {
const { filename, filesize, filetime, filedest } = info;
const row = $('<tr/>');
row.html(`
<td>${filename}</td>
<td>${filesize}</td>
<td>${filetime}</td>
<td>Download</td>
`)
row.appendTo($('table#my-table'));
});
});
})
});
})({{ url_for('.stats') | tojson }});
</script>
</body>
</html>

How to use mailer in Rails 6.1?

I'm currently trying to create a contact us form where users can send a report of any kind to my personal email address. For the sake of this example let's call it my-email-address#email.com.
For the moment I don't care a lot about the user's email. Let's say I'm going to use the following information.
from: "my-email-address#email.com"
to: "my-email-address#email.com"
subject: "a subject name"
STEP 1: I created my form in views/home/contact_us.html.erb with an AJAX POST request:
<form id="sendEmailForm">
<div class="form-group mb-3">
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="Enter your email">
</div>
<div class="form-group mb-3">
<input type="text" class="form-control" id="exampleFormControlInput2" placeholder="Enter a subject (Optional)">
</div>
<div class="form-group mb-3">
<textarea class="form-control" placeholder="Please write your name, company-name, and what you would like to achieve." id="exampleFormControlTextarea3" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-primary mb-2">Send Email</button>
</form>
<script type="text/javascript">
$('#sendEmailForm').on('submit', function(e) {
e.preventDefault();
e.stopPropagation();
let final_json_data = {
email: document.getElementById("exampleFormControlInput1").value,
subject: document.getElementById("exampleFormControlInput2").value,
content: document.getElementById("exampleFormControlTextarea3").value
};
jQuery.ajax({
url: '/home/send_email_to_server',
type: "POST",
data: {emailDetails: final_json_data},
success: function(result) {
alert("ajax request OK!");
},
fail: function(result) {
alert("ajax has failed")
}
});
});
</script>
STEP 2: My Home Controller and routes.rb:
class HomeController < ApplicationController
def contact_us
puts "GETTING THE PAGE !!!!!!!!!!!!!!!!!!!"
end
def send_email_to_server
#emailDetails = params[:emailDetails]
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
puts " Store email details on server"
puts #emailDetails['email']
puts #emailDetails['subject']
puts #emailDetails['content']
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
ContactUsMailer.notify_server_via_email(#emailDetails['email'], #emailDetails['subject']).deliver
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
end
end
Rails.application.routes.draw do
get 'home/contact_us'
post 'home/send_email_to_server'
end
STEP 3: Modified application_mailer.rb to have a default from-email:
class ApplicationMailer < ActionMailer::Base
default from: "my-email-address#email.com"
layout 'mailer'
end
STEP 4: Modified contact_us_mailer.rb to handle the request with the captured parameters:
class ContactUsMailer < ApplicationMailer
def notify_server_via_email(toEmail, aSubject)
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
puts " Trying to send an email . . . "
#email = toEmail
#subject = aSubject
puts #email
puts #subject
puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
mail(
to: #email,
subject: #subject
)
end
end
STEP 4: Then in the views/contact_us_mailer I created a new file called notify_server_via_email.html.erb and added the following content:
<h1> hello world </h1>
So here is what happens in order:
User fills form and submits the button.
AJAX POST REQUEST to /home/send_email_to_server
Server receives request and catches parameters and executes mail() function
However I'm getting the following error:
Started POST "/home/send_email_to_server" for ::1 at 2021-07-03 18:01:00 +0300
Processing by HomeController#send_email_to_server as */*
Parameters: {"emailDetails"=>{"email"=>"my-email-address#email.com", "subject"=>"some new subject", "content"=>"a text example"}}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Store email details on server
my-email-address#email.com
some new subject
a text example
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Trying to send an email . . .
my-email-address#email.com
some new subject
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Rendering layout layouts/mailer.html.erb
Rendering contact_us_mailer/notify_server_via_email.html.erb within layouts/mailer
Rendered contact_us_mailer/notify_server_via_email.html.erb within layouts/mailer (Duration: 0.5ms | Allocations: 70)
Rendered layout layouts/mailer.html.erb (Duration: 1.5ms | Allocations: 241)
ContactUsMailer#notify_server_via_email: processed outbound mail in 14.0ms
Delivered mail 60e07bace69f9_27544024-497#DESKTOP-MQJ3IGG.mail (30045.8ms)
Date: Sat, 03 Jul 2021 18:01:00 +0300
From: my-email-address#email.com
To: my-email-address#email.com
Message-ID: <60e07bace69f9_27544024-497#DESKTOP-MQJ3IGG.mail>
Subject: some new subject
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
/* Email styles need to be inline */
</style>
</head>
<body>
<h1> hello world </h1>
</body>
</html>
Completed 500 Internal Server Error in 30095ms (ActiveRecord: 0.0ms | Allocations: 11373)
EOFError (end of file reached):
app/controllers/home_controller.rb:35:in `send_email_to_server'
I have no idea what is causing the 500 Internal server error. I'm currently working on the development side and I'm aware that I shouldn't be doing this but it's just for testing purposes, I'm not aiming to keep this configuration forever. Also, I came across this StackOverflow Question which is similar with my issue, but there is no clear answer since that was the university wifi preventing an smtp request from working. I'm trying from a home wifi.
Also for additional reference here is my development.rb commands for action_mailer:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'localhost',
:port => 3000
}
config.action_mailer.default_url_options = {host: 'localhost:3000'}
config.action_mailer.perform_caching = false
Error is raised by library net/protocol.rb#227. If you open browser developer tools, you can see it under subtab response for request with status 500 under tab Network.
Error reason: library can not connect to your smtp server that according to your development.rb config config.action_mailer.smtp_settings is located at localhost:3000. At port 3000 is located your web-server, smtp usually is located at port 25, 587, 2525 (if it is running).
You need running smtp server and correctly configured config.action_mailer.smtp_settings on your local computer if you wish to send mail to my-email-address#email.com in development environment.
If you wish to check email, you can look at console or log. Or use gem letter_opener, or use ActionMailer::Preview. See answer at StackOverflow.

Flask Ajax Error 400

i get an error 400 when posting. i'm using flask and sqlalchemy in the backend, and pretty straightforward javascript & jquery
here is the JS:
$.ajax({
url: "/create",
type: "POST",
data: {
question: question,
answer1: answer1,
answer2: answer2,
answer3: answer3,
answer4: answer4,
answer5: answer5,
answer6: answer6,
congress: congress,
session: session,
date: date,
lecture: lecture,
correct: correct
},
success: function(){
console.log("sent");
}, error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
and here is the Flask code:
#app.route('/create', methods=['GET', 'POST'])
def cre():
post = QuestionClass(congress=str(request.form['congress']),
session=str(request.form['session']),
date=str(request.form['date']),
lecture=str(request.form['lecture']),
question=str(request.form['question']),
answer1=str(request.form['answer1']),
answer2=str(request.form['answer2']), answer3=str(request.form['answer3']),
answer4=str(request.form['answer4']), answer5=str(request.form['answer5']),
)
engine = create_engine(sqlite:///DB.db', echo=True)
Session = sessionmaker(bind=engine)
sqlsession = Session()
sqlsession.add(post)
sqlsession.commit()
return 1
and i can't for the life of me figure out what's wrong...
I also had a thorough look, but couldn't find anything obvious. I made a small working example, which does exactly what you hope it should be doing. Try adding stuff to the example till you break it.
from flask import Flask, render_template_string, request, jsonify, url_for
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
info = request.form['question']
print(info)
return jsonify({'what_you_sent': info})
return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div></div>
<script>
$.ajax({
url: "/",
type: "POST",
data: {
question: 'hello?',
answer1: 'hi',
},
success: function(data){
alert(data.what_you_sent);},
error: function(xhr, textStatus, error){
alert('such error')}
});
</script>
</body>
</html>
''')
app.run()
Just a general tip when debugging 400 errors, just access the form elements one by one instead of directly applying them to a model or whatever, it's easier to spot them like that.
like:
print(request.form['question'])
print(request.form['answer1'])
etc...
Also clean your browser cache just in case.
As I have mentioned in my comment what the data object represents is a json object and unlike javascript objects, the keys must be strings see this ref
Change your data object to (am assuming your values are valid JSON data type (string, number, object, array, boolean or null))
EDIT I was answering this question and realized the main problem could be that your data was url-encoded by jquery. If you stringify it like below, it should work. Try it on your original code
data: JSON.stringify({
"question": question,
"answer1": answer1,
"answer2": answer2,
"answer3": answer3,
"answer4": answer4,
"answer5": answer5,
"answer6": answer6,
"congress": congress,
"session": session,
"date": date,
"lecture": lecture,
"correct": correct
}),
Okay, I will make your flask a bit more complicated, but for a good cause. I will make a wtf form (you can make a normal form but I like the additional features of wtf like validation etc)
class QuestionForm(FlaskForm):
question = StringField('question', [validators.InputRequired(message="Please enter a valid entry")])
answer1 = StringField('answer1', [validators.InputRequired(message="Please enter a valid entry")])
answer2 = StringField('answer2', [validators.InputRequired(message="Please enter a valid entry")])
answer3 = StringField('answer3', [validators.InputRequired(message="Please enter a valid entry")])
answer4 = StringField('answer4', [validators.InputRequired(message="Please enter a valid entry")])
answer5 = StringField('answer5', [validators.InputRequired(message="Please enter a valid entry")])
answer6 = StringField('answer6', [validators.InputRequired(message="Please enter a valid entry")])
congress = StringField('congress', [validators.InputRequired(message="Please enter a valid entry")])
session = StringField('session', [validators.InputRequired(message="Please enter a valid entry")])
date = StringField('date', [validators.InputRequired(message="Please enter a valid entry")])
lecture = StringField('lecture', [validators.InputRequired(message="Please enter a valid entry")])
correct = StringField('correct', [validators.InputRequired(message="Please enter a valid entry")])
Be sure to make relvant imports if you go with wtf
from flask_wtf import FlaskForm
from wtforms import Form, BooleanField, StringField, IntegerField, validators, SelectField, TextAreaField, HiddenField
Then I will use werkzeug.datastructures to access the json data (i start with import, import the form as well if it is in a different file from forms import QuestionForm), then access all the values of the form. I am returning all the values in a string just to be sure I am receiving them, am sure you will know how to save to your database from there
from werkzeug.datastructures import MultiDict
#app.route('/create', methods=['POST'])
def cre():
form_data = MultiDict(mapping=request.json)
form = QuestionForm(form_data)
if request.is_json:
question= form.question.data
answer1= form.answer1.data
answer2= form.answer2.data
answer3= form.answer3.data
answer4= form.answer4.data
answer5= form.answer5.data
answer6= form.answer6.data
congress= form.congress.data
ssession= form.session.data
date= form.date.data
lecture= form.lecture.data
correct= form.correct.data
return str(question+' '+answer1+' '+answer2+' '+answer3+' '+answer4+' '+answer5+' '+answer6+' '+congress+' '+ssession+' '+date+' '+lecture+' '+correct)
You can add if form.validate_on_submit(): after the if request.is_json: if you wish to validate the data as per the validators you specify on the form
I am able to get a response with all the values I put in my json object. I am sure if you find this example one that can work for you, you will be able to debug from there (I used ssession because on my testing app i already have session defined)

Simple Django-swampdragon + AngularJS real-time app

I use django-swampdragon + angularjs to create simple django app which shows website requests in real-time.
All of the Django logic is okay, but when I try make it respond in real-time the system kind of fails. I think the problem is in Angular, since I haven't used it before.
So, the django-swampdragon part of code:
# routers.py
from swampdragon import route_handler
from swampdragon.route_handler import ModelRouter
from .serializers import HttpRequestSerializer
from .models import HttpRequest
class HttpRequestRouter(ModelRouter):
serializer_class = HttpRequestSerializer
model = HttpRequest
route_name = 'activity-route'
def get_object(self, **kwargs):
return self.model.objects.get(pk=kwargs['pk'])
def get_query_set(self, **kwargs):
return self.model.all()
route_handler.register(HttpRequestRouter)
The Angular.js part of code
// controllers.js
var ActivityControllers = angular.module('ActivityControllers', []);
ActivityControllers.controller('ActivityCtrl', ['$scope', '$dragon', function ($scope, $dragon) {
$scope.channel = 'httprequests';
$scope.datasource = [];
// Subscribe to the activity router
$dragon.onReady(function() {
$dragon.subscribe('activity-route', $scope.channel, {}).then(function(response) {
this.dataMapper = new DataMapper(response.data);
});
$dragon.getList('activity-route', {}).then(function(response) {
$scope.datasource = response.data
});
});
$dragon.onChannelMessage(function(channels, new_request) {
if (indexOf.call(channels, $scope.channel) > -1) {
$scope.$apply(function() {
$scope.datasource.unshift(new_request);
});
}
});
}]);
And, finally, my template part:
<div ng-controller="ActivityCtrl">
<ul ng-repeat="req in datasource">
<li>
<span class="request_date">{$ req.date $} ...</span>
</li>
</ul>
</div>
When I run server.py and open browser on that url/port (http://localhost:9999/) i have this error (in browser):
Traceback (most recent call last):
File "...lib/python3.4/site-packages/tornado/web.py", line 1323, in _execute
result = self.prepare()
File "...lib/python3.4/site-packages/tornado/web.py", line 2014, in prepare
raise HTTPError(self._status_code)
tornado.web.HTTPError: HTTP 404: Not Found
And also this error on the console:
-------- SwampDragon ------
Running SwampDragon on 127.0.0.1:9999
DRAGON_URL: http://localhost:9999/
Version 0.4.2
Debug: True
Quit the server with ctrl+c
---------------------------
WARNING:tornado.access:404 GET / (127.0.0.1) 206.58ms
And, of course, my page with request don't work either.
PLease help me find the error!
Just to be sure, you are running your django server and your swmapdragon server, correct? As in you are doing both:
python server.py
python manage.py runserver

Why is the URL 404 not found with Django?

I have written a Django script that runs a Python parser to web s*e. I am sending the request to the Django script via AJAX. However, when the Ajax runs, it comes back as 404 not found for the URL. Why is this happening?
My code is below:
Ajax (with jQuery):
//send a `post` request up to AWS, and then
//insert the data into the paths
$.post('/ca', function(data){
//evaluate the JSON
data = eval ("(" + data + ")");
//insert the vars into the DOM
var contentOne;
contentOne = data.bridge_time;
contentOne += 'min delay';
$('#timeone').html(contentOne);
var contentTwo;
contentTwo = data.tunnel_time;
contentTwo += 'min delay';
$('#timetwo').html(contentTwo);
//if this falls through, push an error.
var tunnel_time = data.tunnel_time;
var bridge_time = data.bridge_time;
var tunnel = document.getElementById('tunnel');
var bridge = document.getElementById('bridge');
var tunnelText = document.getElementById('timeone');
var bridgeText = document.getElementById('timetwo');
//algo for the changing icons. Kudos to Vito
if(tunnel_time<bridge_time){
tunnel.src="tunnel3.png";
bridge.src="bridge2r.png";
}else if( bridge_time<tunnel_time){
bridge.src="bridge21.png";
tunnel.src="tunnel2r.png";
}else{
bridge.src="bridge2n.png";
tunnel.src="tunnel2g.png";
}
$.fail(function() {
alert("We're sorry. We are having an error. Check back later.");
});
});
My urls.py:
from django.conf.urls.defaults import *
from views import views
urlpatterns = patterns('',
(r'^/us', views.american_time),
(r'^/ca', views.canadian_time),
)
My urls.py and my views.py are in the same folder, if that makes any difference. They are just titled views.py and urls.py. Thank you!
Try
from django.conf.urls.defaults import *
from views import views
urlpatterns = patterns('',
(r'^/us/$', views.american_time),
(r'^/ca/$', views.canadian_time),
)
Also you have to add the trailing slash in your JavaScript.
I just resolved this: there was an error in my urls.py. My system was having trouble with the .defaults that is was supposed to import from. Also, I didn't have a Django project set up, so It wouldn't import the views.

Categories

Resources