簡體   English   中英

django無法在視圖中創建常規對象,返回500錯誤

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

我在django項目中遇到了ajax請求的問題。 我試圖通過在任何地方添加打印語句來調試視圖代碼,直到我發現它似乎停止並返回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)

(日志記錄調用接受參數並自行進行字符串插值,因此您不需要像使用print那樣使用%運算符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM