Reputation: 171
Hello I'm new to python flask web development. I've been wondering what's wrong with my code, I kept on getting CSRF Token Missing. I am using Flask-WTF version 0.11. There are instances where the validation was successful and when I try to click again the upload button, it just reloads or sometimes pops out a CSRF Token Missing
string above my Text Field. This is only happening when I access in a different domain, it works on my localhost:
This is my partial code for config.py:
class Config:
WTF_CSRF_ENABLED = True
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
This is my code for login.html:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Chase POS - Login{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Login</h1>
</div>
{{ form.hidden_tag() }}
<div class="col-md-4">
{{ wtf.quick_form(form, method="POST", enctype="multipart/form-data") }}
</div>
{% endblock %}
This is my code for views.py:
@main.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(id=form.id.data).first()
if user is not None and user.verify_password(form.password.data):
try:
login_user(user, False)
upload_file()
return redirect(url_for('.login'))
except ValueError:
flash('Row ' + str(counter) + ': Incorrect value detected.')
except TypeError:
flash('Row ' + str(counter) + ': Data type mismatch. Failed to continue transaction.')
except AttributeError:
flash('Row ' + str(counter) + ': Some of the data cannot be found on the database.')
else:
flash('Invalid username or password.')
return render_template('login.html', form=form)
I even tried to disable csrf but still get the same error. Hope you can help me, thanks in advance
Upvotes: 1
Views: 7096
Reputation: 18279
I had the same issue with flask
and wtform
. Adding CsrfProtect(app)
solved it for me.
from flask import Flask
from flask_wtf.csrf import CsrfProtect
app = Flask(__name__)
app.secret_key = 'very secret'
CsrfProtect(app)
In the template, do:
{{ form.hidden_tag() }}
Upvotes: 4
Reputation: 6861
Replace form.hidden_tag()
with form.hidden_tag
. Alternatively, revert back to an older version of Flask-WTF (v0.9) where they still use the brackets in form.hidden_tag()
Upvotes: 1