简体   繁体   中英

500 server error, I have no idea what's wrong, ajax, django

I have these bits of code and I've been at it for hours but I cannot figure what is wrong.

I keep getting a 500 server response, and it wouldn't even start debugging in the view definition when I trigger the ajax.

I'm really at a loss, any help would be fantastic!

    $('.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
}

UPDATE: I don't think syntacticly there are anything wrong with my view, so I took it out and added the traceback, is it something wrong with the csrf token? All of my other ajax functions work

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

I saw ur jquery code and there should not be any errors...

just a wild guess because something similar happened to me before and took me a while to realize it (forgot what the traceback looks like)

You may want to check your urls file and make sure you're not using the same url or the wildcard of an existing url pattern.

From what I can see, your traceback:

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

indicates that ''.join(self._container) part encounters an element that is not a string (NoneType) ie some piece of the form ends up a NoneType and cannot be serialized properly when CSRF field is supposed to be added. Looking at the django code self._container is actually the content if HttpResponse passed in. That means Django tries to add csrfmiddletoken field in the response's form and the regular expression that tried to match the form and insert it somehow ended up catching a NoneType instead of just strings.

The regular expression in question is:

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

I would check the response form you are generating and make sure it is correctly formed. It would also help to step through the csrf code and see exactly where it is catching the NoneType.

Without looking at the view handler and the form code I can't really say more.

Your targeted view should contain this pattern to make AJAX post requests fine:

def target_view(request) if request.method == 'POST': if request.is_ajax():

jQuery's .load() and .get() methods will work fine but to use $.ajax() or $.post() methods you must follow pattern like above in targeting function.

Here my js source function is:

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

Reply me if it fails.

Try doing a rollback when the request is not ajax. You need to rollback or commit when using the commit_manually decorator.

Have you add this csrf protection required code to all your pages with ajax POST requests?

$(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'));
             }
         }
    });
});

It is expalined in docs .

Try this and, please, give some feedback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM