【问题标题】:Django dump JSON dataDjango 转储 JSON 数据
【发布时间】:2011-12-07 05:54:16
【问题描述】:

我正在尝试输入一个单词并通过 ajax 将其显示在页面上。我缺少一些简单的东西......

所以我用 Jquery 发送这样的信息:

$.ajax({
url: url,
type:"POST",
data:{'word': word},
success: function(data){
       //do something 
}
});

信息进入视图并保存到数据库中。当我尝试返回新单词时会出现问题:

def add_word(request, lecture_id):
    l = get_object_or_404(Lecture, pk=lecture_id)
    if request.method == "POST":
        #see if there is a value with p
        if request.POST.has_key('word') and request.POST['word'] != "":
            success = {}
            try:
                oldWord = l.post_set.get(word=request.POST['word'])
            except:
                newWord = l.post_set.create(word=request.POST['word'], count = 1)
                success = {'new': str(newWord.word), 'count': str(newWord.count)}
            else:
                oldWord.count += 1
                oldWord.save()
                success = {'old': str(oldWord.word), 'count': str(oldWord.count)}
            return HttpResponse(json.dumps(success), mimetype="application/javascript")
    return HttpResponse(reverse('post.views.lecture_display', args=(l.id,)))

我收到 500 错误...

[13/Oct/2011 15:14:48] "POST /lecture/3/add HTTP/1.1" 500 66975

【问题讨论】:

  • 那个 500 错误是回溯。您应该在浏览器中访问该 URL 以查看它是什么。
  • 您还必须发布整个视图。

标签: json ajax django post


【解决方案1】:

没有看到回溯,我的猜测是失败的是[其中之一]:

# A) This path is not resolving correctly (see named-URLs in Django's docs)
reverse('post.views.lecture_display', args=(l.id,))

# B) This word has unicode data, which can't simply be passed to ``str``
str(oldWord.word)

直接在浏览器中打开 URL,你会得到默认的 Django 回溯,500 视图。

【讨论】:

  • @captDaylight - 最后是什么异常?
【解决方案2】:

我认为你需要学习调试而不是特定的修复。

  1. 尝试在没有发布数据的情况下打开该网址,看看是否存在语法或名称错误。
  2. 如果问题仍然存在,请使用ipdbpudb 包,在视图中插入以下行并分析代码内部发生的情况:

    def myview(请求,id): 导入ipdb; ipdb.set_trace()

使用 Chrome 开发者工具或 Firebug 查看服务器输出的内容和打开的 url。另请查看Django Debug ToolbarWerkzeug。调试工具栏可以显示所有已渲染的模板和所有局部变量。 Werkzeug 还在浏览器的调用堆栈的任何位置为您提供了一个调试 shell。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2012-06-28
    • 2012-01-08
    相关资源
    最近更新 更多