简体   繁体   中英

Django Ajax form submission pointing to a 403 Forbidden

I'm allowing users to remove posts through ajax. Posts have a boolean field live_until_removed. When set to false, the post disappears.

When clicking remove I'm given a 403, referencing:

xhr.send( ( s.hasContent && s.data ) || null );

How do I get this to run smoothly? Why this this error happening?

js:

$('#removeForm').submit(function() { // catch the form's submit event
    $.ajax({
        data: $(this).serialize(),
        type: $(this).attr('method'), 
        url: $(this).attr('action'),
        success: function(response) {
            $('.close-post').html(response); // update the DIV
            console.log(response);
        },
        error: function(response){
            console.log(response);
        }
    });
    return false;
});

template:

<div class="close-post">
     {% if not post.live_until_removed %}
     <form class="" id="removeForm" method="POST" action="">
          <button type="submit" class="btn">Remove</button>
     </form>
     {% else %}
     <button class="btn">Removed</button>
     {% endif %}
</div>

views.py:

def post(request, id):
    ...
     if request.is_ajax():
          try: 
               post = Post.objects.get(id=id)
               post.live_until_removed = False
               post.save()
               response = simplejson.dumps({"status": "Removed"})
          except:
               pass

You might have missed to send CSRF token in your request. Look at here; Django-Ajax

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