Django 无法在视图中创建常规对象,返回 500 错误

django cannot create a regular object in a view, returns 500 error

本文关键字:对象 返回 错误 常规 创建 视图 Django      更新时间:2023-09-26

我在 django 项目中遇到 ajax 请求的问题。我试图通过在任何地方添加 print 语句来调试视图代码,直到我找到它似乎停止并返回 500 错误的位置。我不知道为什么会发生这种情况,所以我希望有更多经验的人会知道出了什么问题。

我正在使用的javascript库是jQuery(仅用于ajax调用)和GogoMakePlay(GogoMakePlay.com)。

该应用程序是一个基于浏览器的国际象棋游戏,后端在django和javascript(GogoMakePlay)中用于显示棋盘。在这种情况下,将显示棋盘,当我单击棋子时,它应该对 django 视图进行 ajax 调用,该视图返回可能移动的 json。我每次都点击一个棋子,以便执行我的打印功能,我应该能够找到问题,但这次没有。

我的问题与此几乎相同:

无法在 Ajax 发布请求中创建新的 Django 模型对象

除了与他不同的是,我的问题并没有消失。

有问题的观点:

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")

典当码:

 class Pawn(Piece):
   def __init__(self, colour):
     print "creating object"
     self.colour = colour
     print "object created, the colour is: " + colour
 *snip*

AJAX 请求代码:

*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*

我的 Django 控制台输出:

 *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

我知道我可以只用javascript编写代码,但这是一个学校项目,我的目标之一是了解如何进行ajax调用。

我已经在谷歌上搜索了几个小时,只找到了上述与我的问题相关的链接。通常StackOverflow有所有的答案,但在这种情况下,我被迫创建一个帐户,以便我可以问这个问题。如果有类似的问题和我的问题的解决方案,请原谅我。

所以我的问题是:

  1. 您需要更多信息来帮助我吗?如果是这样,您需要知道什么?
  2. 我的 ajax 调用正确吗?
  3. 如果是这样,为什么会给出 500 错误?如果不是,那我做错了什么?
  4. 为什么视图开始执行,但在创建 Pawn 对象后立即停止?

提前谢谢你=)

因此,错误实际上出在调试代码中:

print "created the piece: " + piece 

piece是Pawn的一个实例,正如错误所说,你不能只将字符串与随机对象连接起来。Python 不是 PHP - 它是强类型的,为了做到这一点,你需要将实例转换为它的字符串表示形式。执行此操作的最佳方法是使用字符串格式

print "created the piece: %s" % piece 

这将调用对象的 __unicode__ 方法将其转换为字符串。

请注意,您实际上应该使用日志记录调用而不是打印 - 除此之外,如果您在部署时不小心在代码中留下了 print 语句,则一切都会中断。所以它真的应该是:

logging.info('created the piece: %s', piece)

(日志记录调用采用参数并自行执行字符串内插,因此您不需要像打印那样使用 % 运算符)。