AJAX post方法在Django中失败:404

时间:2016-09-11 19:16:37

标签: jquery ajax django

我在程序中使用jQuery将POST请求发送到我的数据库,以便在Django框架上托管的客户端Javascript游戏中记录用户操作。在添加

之前,我已经收到了403错误
csrfmiddlewaretoken: csrftoken

使用适当填充的csrftoken值,但是当我尝试$.post()时,我现在得到404错误,而不是愉快地按照承诺工作。

抢先一步:是的,如果我将其复制并粘贴到地址栏中,则错误消息声称为404的网址会加载。

urls.py(部分,省略不相关的页面):

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^init/$', views.init, name='init'),
    url(r'^log/$', views.log, name='log')
]

views.py(部分,省略不相关的观点):

from django.shortcuts import get_object_or_404
from django.http import HttpResponse

from .models import Partnership, RunLog

def index(request):
    return render(request, 'mysite/index.html')

def init(request):
    [...]
    return render(request, 'mysite/init.html', args)

def log(request):
    """ This is for logging actions within the blockly-game interface.
        It is called by jQuery code in maze.js every time the user pushes
        the Run button, so we can see how they're doing.
    """
    if request.method == 'POST':
        code = request.POST['usercode']
        status = request.POST['status']
        ps = get_object_or_404(Partnership, name=request.POST['ps'])
        runlog = RunLog.objects.create_runlog(ps.name, status, code)
        runlog.save()
    return HttpResponse('x')

来自maze.js:

console.log(ps);            // works as expected
console.log(Maze.result);   // works as expected
console.log(code);          // works as expected
console.log(csrftoken)      // works as expected

// this gives a 404 with csrfmiddlewaretoken; 403 without
$.post('/mysite/log/',
  {
      csrfmiddlewaretoken: csrftoken,
      ps: path,
      status: Maze.result,
      usercode: code
  }
);

还验证我正确地将RunLog模型添加到我的数据库中,它显示在我的管理视图中,没有任何条目。

我在这里缺少什么?

0 个答案:

没有答案