I'm trying to create a Login form in Flask. But, every time I fill in the information and click "Log In", it gives me an error: 'csrf_token': ['The CSRF token is missing.']}
When I check the webpage code in my browser, it shows that I do have a CSRF token in the form.
<h1>Log In</h1>
<form action="/" method="POST" class="register">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjAyZjNmOGZmMmRhNGIyOWI1YTBiNmVhMzNiYTU3MGUxY2U2ZTAxZmQi.X5V_4A.5EzKomC48Xa0I3iNinFu1yncRak">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjAyZjNmOGZmMmRhNGIyOWI1YTBiNmVhMzNiYTU3MGUxY2U2ZTAxZmQi.X5V_4A.5EzKomC48Xa0I3iNinFu1yncRak">
<div class="username">
<label for="username">Username</label>
<input id="username" name="username" placeholder="8 to 20 characters" required type="text" value="">
</div>
This is my form:
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=8, max=20)],
render_kw={'placeholder': '8 to 20 characters'})
password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Log In')
And this is the route:
@users.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
from app.users.models import User
print('validate on submit')
user = User.query.filter_by(username=form.username.data).first()
flash(user)
print(user)
if user is None:
flash('Invalid username or password', 'error')
return redirect(url_for('login'))
if user is not user.check_password(form.password.data):
flash('Invalid username or password', 'error')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('home')
return redirect(next_page)
print(form.errors)
return render_template('users/login.html', title='Log In', form=form)
I have a config class that does create a secret key, as well:
class Config:
app.config['SECRET_KEY'] = 'era14149dfafjf328491rej1f19914'
The form also contains a hidden_tag and a csrf_token :
<h1>Log In</h1>
<form action="/" method="POST" class="register">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
What am I doing wrong? The form is showing a CSRF token in the webpage code but for some reason, it still doesn't work...
</form>) the tag