CSRF Token missing or invalid. -> First form fails other CSRF Token workdjango: csrf_token for multiple forms and ajax requests on a single pageDjango CSRF check failing with an Ajax POST requestWhat is a CSRF token ? What is its importance and how does it work?csrf token Follow upDjango POST request to my view from Pyres worker - CSRF tokendjango, set csrf token on form in static pagesPOST AJAX DJANGO 403 forbbiden after adding csrf tokenNo CSRF token after Django 1.8 form errorSubmitting ASP.NET MVC CSRF token with $http in AngularJSLaravel csrf token mismatch on ajax post a second timeCSRF protection when not using forms to submit data

Can two figures have the same area, perimeter, and same number of segments have different shape?

Why did Saturn V not head straight to the moon?

How can I make sure my players' decisions have consequences?

Examples of solving for unknowns using equivalence relations that are not equality, inequality, or boolean truth?

"I you already know": is this proper English?

Can I pay with HKD in Macau or Shenzhen?

Why did NASA use Imperial units?

Are glider winch launches rarer in the USA than in the rest of the world? Why?

What exactly makes a General Products hull nearly indestructible?

Why do people say "I am broke" instead of "I am broken"?

Why did computer video outputs go from digital to analog, then back to digital?

Short story about a group of sci-fi writers sitting around discussing their profession

Grid/table with lots of buttons

Why are off grid solar setups only 12, 24, 48 VDC?

Would it be a good idea to memorize relative interval positions on guitar?

Does a grappled creature need to use an action to escape grapple if grappler is stunned?

Explanation for a joke about a three-legged dog that walks into a bar

How can I receive packages while in France?

Who has jurisdiction for a crime committed in an embassy?

Direct revelation mechanism's sets of strategies and types

What are the exact meanings of roll, pitch and yaw?

Does static fire reduce reliability?

Extrapolation v. Interpolation

Which creatures count as green creatures?



CSRF Token missing or invalid. -> First form fails other CSRF Token work


django: csrf_token for multiple forms and ajax requests on a single pageDjango CSRF check failing with an Ajax POST requestWhat is a CSRF token ? What is its importance and how does it work?csrf token Follow upDjango POST request to my view from Pyres worker - CSRF tokendjango, set csrf token on form in static pagesPOST AJAX DJANGO 403 forbbiden after adding csrf tokenNo CSRF token after Django 1.8 form errorSubmitting ASP.NET MVC CSRF token with $http in AngularJSLaravel csrf token mismatch on ajax post a second timeCSRF protection when not using forms to submit data






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















So I have a site with multiple buttons. These buttons are inside forms and use this CSRF . However the first button won't work.



This is a snippet of how the HTML looks like.



<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="startVm" class="btn btn-default btn-block d-none d-md-block">StartVM</button>
</form>
<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="stopVm" class="btn btn-default btn-block d-none d-md-block">StopVM</button>
</form>


And this is the Ajax function that I use.



$('#post-form').on('submit', function(e)
e.preventDefault();
console.log("form submitted!") // sanity check
post();
);
// AJAX for posting
function post()
console.log("create post is working!") // sanity check
$.ajax(
url : '', // the endpoint
type : 'post', // http method
data : ,
csrfmiddlewaretoken: ' csrf_token ',
contentType: 'application/x-www-form-urlencoded',
processData: true,
// handle a successful response
success : function()
alert("Thank you for your comment!");
console.log("success"); // another sanity check
,

// handle a non-successful response
error : function(xhr,errmsg,err)
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console

);
;


So as I said. The button StartVM won't work and it returns a 403 error.(Forbidden (CSRF token missing or incorrect.): /)
The second one however works without a problem.



This is the code in the view.py



def post (self, request):
if request.method == 'POST' and 'startVm' in request.POST:
print("startVM button")
return HttpResponse("",
content_type='application/json', status=204)
if request.method == 'POST' and 'stopVm' in request.POST:
print("stopVM button");
return HttpResponse("",
content_type='application/json', status=204)
return HttpResponse("",
content_type='application/json')


I am returning status 204 because e.preventDefault() won't work and it refreshes the whole site if I click on a button.










share|improve this question






















  • A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

    – Ben Jordan
    Mar 26 at 19:40

















1















So I have a site with multiple buttons. These buttons are inside forms and use this CSRF . However the first button won't work.



This is a snippet of how the HTML looks like.



<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="startVm" class="btn btn-default btn-block d-none d-md-block">StartVM</button>
</form>
<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="stopVm" class="btn btn-default btn-block d-none d-md-block">StopVM</button>
</form>


And this is the Ajax function that I use.



$('#post-form').on('submit', function(e)
e.preventDefault();
console.log("form submitted!") // sanity check
post();
);
// AJAX for posting
function post()
console.log("create post is working!") // sanity check
$.ajax(
url : '', // the endpoint
type : 'post', // http method
data : ,
csrfmiddlewaretoken: ' csrf_token ',
contentType: 'application/x-www-form-urlencoded',
processData: true,
// handle a successful response
success : function()
alert("Thank you for your comment!");
console.log("success"); // another sanity check
,

// handle a non-successful response
error : function(xhr,errmsg,err)
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console

);
;


So as I said. The button StartVM won't work and it returns a 403 error.(Forbidden (CSRF token missing or incorrect.): /)
The second one however works without a problem.



This is the code in the view.py



def post (self, request):
if request.method == 'POST' and 'startVm' in request.POST:
print("startVM button")
return HttpResponse("",
content_type='application/json', status=204)
if request.method == 'POST' and 'stopVm' in request.POST:
print("stopVM button");
return HttpResponse("",
content_type='application/json', status=204)
return HttpResponse("",
content_type='application/json')


I am returning status 204 because e.preventDefault() won't work and it refreshes the whole site if I click on a button.










share|improve this question






















  • A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

    – Ben Jordan
    Mar 26 at 19:40













1












1








1








So I have a site with multiple buttons. These buttons are inside forms and use this CSRF . However the first button won't work.



This is a snippet of how the HTML looks like.



<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="startVm" class="btn btn-default btn-block d-none d-md-block">StartVM</button>
</form>
<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="stopVm" class="btn btn-default btn-block d-none d-md-block">StopVM</button>
</form>


And this is the Ajax function that I use.



$('#post-form').on('submit', function(e)
e.preventDefault();
console.log("form submitted!") // sanity check
post();
);
// AJAX for posting
function post()
console.log("create post is working!") // sanity check
$.ajax(
url : '', // the endpoint
type : 'post', // http method
data : ,
csrfmiddlewaretoken: ' csrf_token ',
contentType: 'application/x-www-form-urlencoded',
processData: true,
// handle a successful response
success : function()
alert("Thank you for your comment!");
console.log("success"); // another sanity check
,

// handle a non-successful response
error : function(xhr,errmsg,err)
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console

);
;


So as I said. The button StartVM won't work and it returns a 403 error.(Forbidden (CSRF token missing or incorrect.): /)
The second one however works without a problem.



This is the code in the view.py



def post (self, request):
if request.method == 'POST' and 'startVm' in request.POST:
print("startVM button")
return HttpResponse("",
content_type='application/json', status=204)
if request.method == 'POST' and 'stopVm' in request.POST:
print("stopVM button");
return HttpResponse("",
content_type='application/json', status=204)
return HttpResponse("",
content_type='application/json')


I am returning status 204 because e.preventDefault() won't work and it refreshes the whole site if I click on a button.










share|improve this question














So I have a site with multiple buttons. These buttons are inside forms and use this CSRF . However the first button won't work.



This is a snippet of how the HTML looks like.



<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="startVm" class="btn btn-default btn-block d-none d-md-block">StartVM</button>
</form>
<form method="post" id="post-form">
% csrf_token %
<button type="submit" name="stopVm" class="btn btn-default btn-block d-none d-md-block">StopVM</button>
</form>


And this is the Ajax function that I use.



$('#post-form').on('submit', function(e)
e.preventDefault();
console.log("form submitted!") // sanity check
post();
);
// AJAX for posting
function post()
console.log("create post is working!") // sanity check
$.ajax(
url : '', // the endpoint
type : 'post', // http method
data : ,
csrfmiddlewaretoken: ' csrf_token ',
contentType: 'application/x-www-form-urlencoded',
processData: true,
// handle a successful response
success : function()
alert("Thank you for your comment!");
console.log("success"); // another sanity check
,

// handle a non-successful response
error : function(xhr,errmsg,err)
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console

);
;


So as I said. The button StartVM won't work and it returns a 403 error.(Forbidden (CSRF token missing or incorrect.): /)
The second one however works without a problem.



This is the code in the view.py



def post (self, request):
if request.method == 'POST' and 'startVm' in request.POST:
print("startVM button")
return HttpResponse("",
content_type='application/json', status=204)
if request.method == 'POST' and 'stopVm' in request.POST:
print("stopVM button");
return HttpResponse("",
content_type='application/json', status=204)
return HttpResponse("",
content_type='application/json')


I am returning status 204 because e.preventDefault() won't work and it refreshes the whole site if I click on a button.







ajax django csrf






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 15:24









Rhe WiRhe Wi

83 bronze badges




83 bronze badges












  • A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

    – Ben Jordan
    Mar 26 at 19:40

















  • A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

    – Ben Jordan
    Mar 26 at 19:40
















A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

– Ben Jordan
Mar 26 at 19:40





A similar problem was discussed before here: stackoverflow.com/questions/31866435/…

– Ben Jordan
Mar 26 at 19:40












1 Answer
1






active

oldest

votes


















0














Firstly, ids should be unique, but you have id="post-form" on two separate forms.



You could do class="post-form" instead, and change your JS to use .post-form.



Or, for the template in your question, you could have a single <form> tag that contains both buttons.



Next, you need to include the CSRF token inside the form data.



data : 'csrfmiddlewaretoken': ' csrf_token ',


Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.






share|improve this answer























  • Thank you, that was helpful!

    – Rhe Wi
    Mar 27 at 10:58










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55360753%2fcsrf-token-missing-or-invalid-first-form-fails-other-csrf-token-work%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Firstly, ids should be unique, but you have id="post-form" on two separate forms.



You could do class="post-form" instead, and change your JS to use .post-form.



Or, for the template in your question, you could have a single <form> tag that contains both buttons.



Next, you need to include the CSRF token inside the form data.



data : 'csrfmiddlewaretoken': ' csrf_token ',


Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.






share|improve this answer























  • Thank you, that was helpful!

    – Rhe Wi
    Mar 27 at 10:58















0














Firstly, ids should be unique, but you have id="post-form" on two separate forms.



You could do class="post-form" instead, and change your JS to use .post-form.



Or, for the template in your question, you could have a single <form> tag that contains both buttons.



Next, you need to include the CSRF token inside the form data.



data : 'csrfmiddlewaretoken': ' csrf_token ',


Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.






share|improve this answer























  • Thank you, that was helpful!

    – Rhe Wi
    Mar 27 at 10:58













0












0








0







Firstly, ids should be unique, but you have id="post-form" on two separate forms.



You could do class="post-form" instead, and change your JS to use .post-form.



Or, for the template in your question, you could have a single <form> tag that contains both buttons.



Next, you need to include the CSRF token inside the form data.



data : 'csrfmiddlewaretoken': ' csrf_token ',


Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.






share|improve this answer













Firstly, ids should be unique, but you have id="post-form" on two separate forms.



You could do class="post-form" instead, and change your JS to use .post-form.



Or, for the template in your question, you could have a single <form> tag that contains both buttons.



Next, you need to include the CSRF token inside the form data.



data : 'csrfmiddlewaretoken': ' csrf_token ',


Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 16:02









AlasdairAlasdair

196k28 gold badges342 silver badges330 bronze badges




196k28 gold badges342 silver badges330 bronze badges












  • Thank you, that was helpful!

    – Rhe Wi
    Mar 27 at 10:58

















  • Thank you, that was helpful!

    – Rhe Wi
    Mar 27 at 10:58
















Thank you, that was helpful!

– Rhe Wi
Mar 27 at 10:58





Thank you, that was helpful!

– Rhe Wi
Mar 27 at 10:58








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55360753%2fcsrf-token-missing-or-invalid-first-form-fails-other-csrf-token-work%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해