简体   繁体   中英

Forbidden (CSRF token missing or incorrect.)

I've searched through similar questions, but nothing seems relevant to my situation.

Why does this code work fine:

<form action="/signup/" method="post">
{% csrf_token %}
[FORM]
</form>

but

<form id="signup-form">
  {% csrf_token %}
[FORM]
  </form>

<script type="text/javascript">
$(function() {
$(".submit-signup").on("click", function() {
    var user = $("#signup_form").serialize();
    console.log(user);
    $.post("/signup/", user, function() {
    });
});
});
 </script>

not work?

Here is signup in views.py:

@requires_csrf_token
def signup(request):
[STUFF]

return render(request, 'signup.html', {[STUFF}})

What else can I provide that would help? Basically I am trying to take a page and turn it into a modal that does the same thing.

Thanks!

you are doing an ajax post call for which you need to give csrf token also:

$.post("/signup/", {
    user: user, 
    csrfmiddlewaretoken: '{{ csrf_token }}'
}, function() {
   // success todo
}, function(){
   // fail todo
});

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