【问题标题】:500 server error, I have no idea what's wrong, ajax, django500 服务器错误,我不知道出了什么问题,ajax,django
【发布时间】:2011-11-14 18:03:55
【问题描述】:

我有这些代码,我已经用了好几个小时了,但我不知道哪里出了问题。

我不断收到 500 服务器响应,当我触发 ajax 时,它甚至不会在视图定义中开始调试。

我真的很茫然,任何帮助都会很棒!

    $('.cheque_info_edit_button').live('click', function(){

var new_cheque = {
    // cheque number is taken from the cell, not input box for this one.
    cheque_no: $(this).closest('td').closest('tr').find('.inv_prof_cheque_no').text(),
    their_bank: $(this).closest('td').closest('tr').find('.new_their_bank_input_ajax').val(),
    our_bank: $(this).closest('td').closest('tr').find('.new_our_bank_input_ajax').val(),
    cash_in_date: $(this).closest('td').closest('tr').find('.new_cash_in_date_input_ajax').val(),
    cheque_amount: $(this).closest('td').closest('tr').find('.new_cheque_amount_input_ajax').val(),
    info_type: 'edit'
   };

    var cheque_json = JSON.stringify(new_cheque);
    $.ajax({
       type: 'POST',
       url: '/best_choose/invoice/profile/inv_add_or_edit_cheque/',
       data: cheque_json,
       success: function(){
       // do stuff
}

更新:我认为我的观点在语法上没有任何问题,所以我将其取出并添加了回溯,是 csrf 令牌有问题吗?我所有的其他 ajax 函数都可以工作

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/best_choose/invoice/profile/inv_add_or_edit_cheque/

Django Version: 1.3
Python Version: 2.7.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'SY_SYSTEM.sy_system',
 'django.contrib.humanize']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.csrf.CsrfResponseMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


 Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  178.                 response = middleware_method(request, response)
 File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/middleware/csrf.py" in process_response
  287.             response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/http/__init__.py" in _get_content
  596.         return smart_str(''.join(self._container), self._charset)

Exception Type: TypeError at /best_choose/invoice/profile/inv_add_or_edit_cheque/
Exception Value: sequence item 0: expected string, NoneType found

【问题讨论】:

  • 您可能需要检查服务器错误日志。可能是后端脚本出现异常或语法错误。
  • 我在本地运行,它只是给我一个 500 错误
  • 很明显,因为您明确地捕获并消除了所有异常。不要那样做。去掉 try/except,你会在 Firebug 中看到 traceback。
  • 谢谢,我收到 TypeError 并且在回溯中我收到指向此行 response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content) 的错误,但我添加了 csrf ajax 令牌和其他 ajax 调用工作
  • 也许发布视图会有所帮助。

标签: jquery python ajax django


【解决方案1】:

我看到了你的 jquery 代码,应该没有任何错误...

只是一个疯狂的猜测,因为类似的事情以前发生在我身上,我花了一段时间才意识到它(忘记了回溯是什么样子)

您可能需要检查您的 urls 文件并确保您没有使用相同的 url 或现有 url 模式的通配符。

【讨论】:

  • 我不敢相信,我正在查看 url 列表,就是这样!
【解决方案2】:

据我所知,您的回溯:

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/http/__init__.py" in _get_content
   596.         return smart_str(''.join(self._container), self._charset)

Exception Type: TypeError at /best_choose/invoice/profile/inv_add_or_edit_cheque/
Exception Value: sequence item 0: expected string, NoneType found

表示''.join(self._container) 部分遇到了一个不是字符串 (NoneType) 的元素,即表单的某些部分以 NoneType 结尾,并且在应该添加 CSRF 字段时无法正确序列化。查看 django 代码self._container 实际上是 HttpResponse 传入时的内容。这意味着 Django 尝试在响应的表单中添加 csrfmiddletoken 字段,并且尝试匹配表单并以某种方式插入它的正则表达式最终捕获了 NoneType 而不是只是字符串。

有问题的正则表达式是:

_POST_FORM_RE = \
re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) 

我会检查您生成的回复表单并确保其格式正确。它还有助于单步执行 csrf 代码并准确查看它捕获 NoneType 的位置。

如果不查看视图处理程序和表单代码,我真的不能多说。

【讨论】:

    【解决方案3】:

    当请求不是 ajax 时尝试回滚。使用 commit_manually 装饰器时需要回滚或提交。

    【讨论】:

    • 感谢您的回答,但我认为情况并非如此,我有其他没有回滚的 ajax 视图并且它有效。不过,我尝试了您建议的解决方案,但结果相同。
    【解决方案4】:

    您是否使用 ajax POST 请求将这个 csrf 保护所需代码添加到所有页面?

    $(document).ready(function(){    
        $.ajaxSetup({
             beforeSend: function(xhr, settings){
                 function getCookie(n) {
                     var cookieValue = null;
                     if(document.cookie&&document.cookie != ''){
                         var cookies = document.cookie.split(';');
                         for(var i = 0; i < cookies.length; i++){
                             var cookie = jQuery.trim(cookies[i]);
                             if(cookie.substring(0, n.length + 1) == (n + '=')){
                                 cookieValue = decodeURIComponent(cookie.substring(n.length + 1));
                                 break;
                             }
                         }
                     }
                     return cookieValue;
                 }
                 if(!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))){
                     xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                 }
             }
        });
    });
    

    docs 中进行了说明。

    试试这个,请提供一些反馈。

    【讨论】:

    • 是的,我所有的其他 Ajax 调用都很好......我得到了一个令牌,我开始认为我这样做很愚蠢......
    【解决方案5】:

    您的目标视图应包含此模式以使 AJAX 发布请求正常:

    定义目标视图(请求) 如果 request.method == 'POST': if request.is_ajax():

    jQuery 的 .load() 和 .get() 方法可以正常工作,但要使用 $.ajax() 或 $.post() 方法,您必须在目标函数中遵循上述模式。

    这里我的js源函数是:

    $.ajax({
         type: 'POST',
         url: '/target view url/',
         success: function(data){
             alert('it works');
         }
    });
    

    如果失败请回复我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2023-03-17
      相关资源
      最近更新 更多