I’m having a problem with a ajax request in a django project. I have tried to debug the view code by add print statements everywhere until I found where it just seems to stop and return a 500 error. I don’t know why this is happening so I was hoping someone with a bit more experience would know what is going wrong.
The javascript libraries I’m using are jQuery (only for the ajax call though) and GogoMakePlay (GogoMakePlay.com)
The application is a browser based chess game with a backend in django and javascript (GogoMakePlay) for displaying the chess board. In this situation the chess board is displayed and when I click on a piece it is supposed to make an ajax call to a django view which returns a json of the possible moves. I click on a pawn piece every time so that my print functions are executed and I should have been able to find the problem but not this time.
My problem is pretty much the same as this one:
Cannot create new Django model object within Ajax post request
except unlike him, my problem did not just disappear.
the view in question:
def get_move_options(request):
if request.POST:
# initialise some variables based on the request type
pieceType = request.POST.get("pieceType")
pieceColour = request.POST.get("pieceColour")
pieceRow = request.POST.get("row")
pieceColumn = request.POST.get("column")
gameId = request.POST.get("gameId")
game = Game.objects.get(pk=gameId)
moves = Move.objects.filter(game=game)
print "initialised all the variables"
# check what type of piece it is
if pieceType == "pawn":
print "colour:" + pieceColour
piece = Pawn(pieceColour)
print "created the piece: " + piece # <-- this is never executed
elif pieceType == "king":
piece = King(pieceColour)
elif pieceType == "queen":
piece = Queen(pieceColour)
elif pieceType == "bishop":
piece = Bishop(pieceColour)
elif pieceType == "knight":
piece = Knight(pieceColour)
elif pieceType == "rook":
piece = Rook(pieceColour)
print "created the piece: " + piece
# make a new board and apply the moves to it
board = Board()
for move in moves:
board.makeMove(move)
print "made all the moves"
# get the possible moves
responseList = piece.getMoveOptions(pieceColumn, pieceRow, board)
return HttpResponse(json.dumps(responseList), mimetype="application/javascript")
the Pawn code:
class Pawn(Piece):
def __init__(self, colour):
print "creating object"
self.colour = colour
print "object created, the colour is: " + colour
*snip*
the ajax request code:
*snip*
// get the csrf_token from the page TODO there must be a better way of doing this
var csrf_token = document.getElementById("csrf_token").getElementsByTagName("input")[0].value;
// add the variables to the post data
var data = {
"gameId" : gameId,
"pieceType" : piece.S.type,
"pieceColour" : piece.S.colour,
"column" : column,
"row" : row,
};
var url = "ajax/getMoveOptions";
// make the ajax call
$.ajax({
type : 'POST',
// add the csrf_token or we will get a 403 response
headers : {
"X-CSRFToken" : csrf_token
},
url : url,
data : data,
dataType : "json",
success : function(json) {
// loop through the json list
for(var i = 0; i < json.length; i++) {
// change the square colour of the options
var x = json[i]["row"];
var y = json[i]["column"];
var option = G.O["square" + y + x];
if(y % 2 == x % 2) {
var squareColour = "white";
} else {
var squareColour = "black";
}
option.setSrc("/static/images/board/" + squareColour + "Option.png").draw();
}
},
error : alert("I have now seen this too many times"),
});
*snip*
my django console output:
*snip*
[01/Jun/2012 02:07:45] "GET /static/images/chess_pieces/white/king.png HTTP/1.1" 200 1489
initialised all the variables
colour:white
creating object
object created, the colour is: white
[01/Jun/2012 02:07:48] "POST /game/ajax/getMoveOptions HTTP/1.1" 500 10331
I know that I could just write the code in the javascript instead, but this is a school project and one of my goals was to understand how to make ajax calls.
I have been googling this for hours and found only the aforementioned link that relates to my problem. Usually StackOverflow has ALL the answers, but in this case I have been forced to create an account so that I can ask this question. Please forgive me if there is a similar question with a solution to my problem.
So my questions are:
- Do you require more information to help me? If so what do you need to know?
- Is my ajax call correct?
- If so, why is it giving a 500 error? If not, then what am I doing wrong?
- Why does the view start executing but stop immediately after the Pawn object has been created?
Thank you in advance =)
So, the error is actually in your debugging code:
pieceis an instance of Pawn, and as the error says, you can’t just concatenate strings with random objects. Python is not PHP – it is strongly typed, and in order to do this you need to convert the instance to its string representation. The best way to do this is to use string formattingwhich will call the object’s
__unicode__method to convert it to a string.Note that you should really be using logging calls rather than prints – apart from anything else, if you accidentally leave a print statement in your code when you deploy, everything will break. So it should really be:
(logging calls take the arguments and do the string interpolation themselves, so you don’t need to use the
%operator as with print).