简体   繁体   English

django请求ajax发布不起作用

[英]django request ajax post not working

I am trying to delete an object from my database using ajax. 我正在尝试使用ajax从数据库中删除对象。 What is happening is that in my view, my request.is_ajax() is returning false always. 发生的事情是,在我看来,我的request.is_ajax()始终返回false。 I don't know why that is happening because I used the same jquery code for my other project where it was working. 我不知道为什么会这样,因为我在其他项目中使用了相同的jquery代码。

Here is my code: 这是我的代码:

Jquery: jQuery:

$('.delete').on('click', function(e){
    e.preventDefault();
   console.log("clicked me");
   var clicked = $(this);
   parent = clicked.parents('.attribute');
    var type = parent.find('input[type=hidden]').val();
    console.log("type", type);
    $.ajax({
        type: 'POST',
        url: location.href,
        data: {'delete': true, 'product_attr_type': type},
        beforeSend: function(){
            console.log('posting');
        }
    }).success(function(response, textStatus, jqXHR){
            parent.hide('slow');
    }).error(function(response, textStatus, jqXHR){
        console.log(response);
    });
});

HTML: HTML:

<form class="smart-form" method="post" action="">
{% csrf_token %}
   <div class="row">
       <section class="col col-2">
          <label class="label">
              Product Attributes
          </label>
          {% if product_attributes %}
              {% for attributes in product_attributes %}
                   <div class="col attribute">
                       <input type="hidden" value="{{ attributes.attribute_type }}">
                       Attribute Type<input type="text" value="{{ attributes.attribute_type }}" name="type[]">
                       Attribute Value<input type="text" value="{{ attributes.value }}" name="value[]">
                       <div class="delete" id="delete_{{ image.pk }}" style="float: right"><i><a>X</a></i></div>
                   </div>
              {% endfor %}
          {% endif %}
       </section>
    </div>
</form>

View: 视图:

def edit_product(request, *args, **kwargs):
    template = 'catalog/edit_product.html'
    print "request",  request.is_ajax()
    try:
        product_pk = kwargs.get('product_pk')
        product = Product.objects.get(pk=product_pk)
    except ProductDoesNotExist:
        raise ProductDoesNotExist('Matching product does not exist.')

    if request.method == 'GET':
        product_form = EditProductForm(instance=product)
        attributes = product.product_attributes
        return render(request, template, {'form': product_form, 'product_attributes': attributes})
    elif request.method == 'POST':
        print "going to check for ajax req"
        if request.is_ajax():
            print "ajax req"
            if request.POST.get('delete'):
                product_attr_type = request.POST.get('product_attr_type')
                print "product_attr_type", product_attr_type
                #product.deactivate_product_attribute(product_attr_type)
                product.is_active = False
                product.save()
            return get_json_response({'msg': 'Product Attribute Deleted Successfully'})
        else:
            attr_type_list = request.POST.getlist('type[]')
            attr_value_list = request.POST.getlist('value[]')
            attribute_types = request.POST.getlist('attribute_type[]')
            attribute_values = request.POST.getlist('attribute_value[]')
            product_form = EditProductForm(request.POST, instance=product)
            if product_form.is_valid():
                form = product_form.save(commit=False)
                for type, value in itertools.izip_longest(attr_type_list, attr_value_list):
                    form.update_or_create_product_attribute(type, value)
                form.save()
                return render(request, template, {'form_saved': 'Product updated successfully!!'})
            else:
                return render(request, template, {'form': product_form})

As you can notice, I have csrf_token in my html form. 如您所见,我的html表单中有csrf_token。 My view is working for normal post but the ajax post is not working.. I have been trying to find the problem since morning but it is just not working. 我的观点适用于普通帖子,但ajax帖子不起作用..自从早上以来,我一直在尝试查找问题,但是它没有起作用。

Please help. 请帮忙。

Request : 要求:

request False <WSGIRequest
path:/catalog/products/5459c34218a3b30fa82ce983/edit/,
GET:<QueryDict: {}>,
POST:<QueryDict: {}>,
COOKIES:{'csrftoken': 'xGMtKYU29bkbA2GKVo5zJblNTRzbZ3Uz'},
META:{'CELERY_LOADER': 'djcelery.loaders.DjangoLoader',
 'CLASSPATH': '/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/bootstrap.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/extensions.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/util.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/jdom.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/log4j.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/trove4j.jar:/home/ankita/tar_files/pycharm-3.4.1/bin/../lib/jna.jar',
 'COMPIZ_CONFIG_PROFILE': 'ubuntu',
 'CONTENT_LENGTH': '',
 'CONTENT_TYPE': 'text/plain',
 u'CSRF_COOKIE': u'xGMtKYU29bkbA2GKVo5zJblNTRzbZ3Uz',
 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-bGHj7ypAA4,guid=edd262eeb415f7bed2434b1100000065',
 'DEFAULTS_PATH': '/usr/share/gconf/ubuntu.default.path',
 'DESKTOP_SESSION': 'ubuntu',
 'DISPLAY': ':0',
 'DJANGO_SETTINGS_MODULE': 'catalog_service.settings',
 'GATEWAY_INTERFACE': 'CGI/1.1',
 'GDMSESSION': 'ubuntu',
 'GIO_LAUNCHED_DESKTOP_FILE': '/home/ankita/.local/share/applications/jetbrains-pycharm.desktop',
 'GIO_LAUNCHED_DESKTOP_FILE_PID': '2385',
 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated',
 'GNOME_KEYRING_CONTROL': '/tmp/keyring-tx9ufr',
 'GNOME_KEYRING_PID': '1930',
 'GPG_AGENT_INFO': '/tmp/keyring-tx9ufr/gpg:0:1',
 'HOME': '/home/ankita',
 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
 'HTTP_CACHE_CONTROL': 'max-age=0',
 'HTTP_CONNECTION': 'keep-alive',
 'HTTP_COOKIE': 'csrftoken=xGMtKYU29bkbA2GKVo5zJblNTRzbZ3Uz',
 'HTTP_HOST': 'localhost:8000',
 'HTTP_REFERER': 'http://localhost:8000/catalog/products/',
 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36',
 'LANG': 'en_IN',
 'LANGUAGE': 'en_IN:en',
 'LD_LIBRARY_PATH': '/home/ankita/tar_files/pycharm-3.4.1/bin:',
 'LOGNAME': 'ankita',
 'MANDATORY_PATH': '/usr/share/gconf/ubuntu.mandatory.path',
 'NODE_PATH': '/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript',
 'PATH': '/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games',
 'PATH_INFO': u'/catalog/products/5459c34218a3b30fa82ce983/edit/',
 'PWD': '/home/ankita/nuvo_dev/peppertap/catalog_service',
 'PYCHARM_DJANGO_MANAGE_MODULE': 'manage',
 'PYTHONPATH': '/home/ankita/nuvo_dev/peppertap/catalog_service',
 'PYTHONUNBUFFERED': '1',
 'QUERY_STRING': '',
 'REMOTE_ADDR': '127.0.0.1',
 'REMOTE_HOST': '',
 'REQUEST_METHOD': 'GET',
 'RUN_MAIN': 'true',
 'SCRIPT_NAME': u'',
 'SERVER_NAME': 'localhost',
 'SERVER_PORT': '8000',
 'SERVER_PROTOCOL': 'HTTP/1.1',
 'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.7.3',
 'SESSION_MANAGER': 'local/ankita-300E5E-300E4E-300E5V-300E4V:@/tmp/.ICE-unix/1941,unix/ankita-300E5E-300E4E-300E5V-300E4V:/tmp/.ICE-unix/1941',
 'SHELL': '/bin/bash',
 'SHLVL': '1',
 'SSH_AGENT_PID': '1977',
 'SSH_AUTH_SOCK': '/tmp/keyring-tx9ufr/ssh',
 'TZ': 'Asia/Kolkata',
 'UBUNTU_MENUPROXY': 'libappmenu.so',
 'USER': 'ankita',
 'XAUTHORITY': '/home/ankita/.Xauthority',
 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg',
 'XDG_CURRENT_DESKTOP': 'Unity',
 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/',
 'XDG_SEAT_PATH': '/org/freedesktop/DisplayManager/Seat0',
 'XDG_SESSION_COOKIE': '10ec76f99f8a073167a9d3230000000a-1415772321.260333-1476791199',
 'XDG_SESSION_PATH': '/org/freedesktop/DisplayManager/Session0',
 '_': '/home/ankita/nuvo_dev/peppertap/catalog_service/env/bin/python',
 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x7fe134578270>,
 'wsgi.file_wrapper': <class wsgiref.util.FileWrapper at 0x363b738>,
 'wsgi.input': <socket._fileobject object at 0x38b6ad0>,
 'wsgi.multiprocess': False,
 'wsgi.multithread': True,
 'wsgi.run_once': False,
 'wsgi.url_scheme': 'http',
 'wsgi.version': (1, 0)}>

My logs in jquery script are also printing. 我在jquery脚本中的日志也正在打印。 ajax is being sent but nothing is happening in the view. 发送了ajax,但视图中没有任何反应。

I get this log in my ajax's error portion : 我在ajax的错误部分中得到了此日志:

POST http://localhost:8000/catalog/products/5459c34218a3b30fa82ce983/edit/ 403 (FORBIDDEN)

我认为这是因为您没有在ajax请求中发送csrf_token。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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