Reputation: 679
Following the documentation of flask-wtf (v. 0.14.2, python 3.4.6) here I get a CSRF token is missing
400 error when reacting on a onchange
event from a simple radio button.
<script type="text/javascript">
// Send the status of the radio buttons using AJAX
function radio_changed(){
var csrf_token = "{{ csrf_token() }}";
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
var radioValue = $("input[class=radios]:checked").val();
//alert(radioValue);
$.ajax({
url: '/_radio_update',
data: {value:radioValue},
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
</script>
then later
<form method=post action="">
{{ form.csrf_token }}
...
on the Flask side:
...
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.secret_key = 'shhhhhhh!'
csrf = CSRFProtect(app)
@app.route('/_radio_update', methods=['GET', 'POST'])
def _radio_update(radiostatus):
print(radiostatus)
...
am I missing something?
Upvotes: 1
Views: 4761
Reputation: 679
It seems that there is a difference between Forms
imported from wtforms
and the one imported from flask.ext.wtf
which according to the note at the end of the documentation causes the problem.
After dealing with the the deprecation notice, finally I changed the line:
from wtforms import Form, RadioField, SubmitField, validators
class InputForm(Form):
...
to
from wtforms import RadioField, SubmitField, validators
from flask_wtf import FlaskForm
class InputForm(FlaskForm):
...
this solved the problem for me.
Upvotes: 3