django请求ajax帖子不工作

时间:2014-11-12 11:06:54

标签: jquery ajax django django-views

我正在尝试使用ajax从我的数据库中删除一个对象。发生的事情是,在我看来,我的request.is_ajax()总是返回false。我不知道为什么会这样,因为我在我工作的其他项目中使用了相同的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:

<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>

查看:

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})

你可以注意到,我的html表单中有csrf_token。我的观点是正常的帖子,但是ajax帖子没有用。我从早上起就试图找到问题但是它没有用。

请帮忙。

请求:

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)}>

我在jquery脚本中的日志也在打印。 ajax正在发送,但视图中没有发生任何事情。

我将此日志记录在我的ajax错误部分中:

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

1 个答案:

答案 0 :(得分:0)

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