First, I'm new to python and Flask, so I'm sorry if my question is dumb. I search it but never found an answer (which should be an "easy" one I guess).
I wanted to add a contact page in my website, I found this tutorial so I followed it. Everything worked fine until the forms validation. I only use Required and form.validate() always returned false. If I don't touch my code, and I remove every Required in the form class, it works fine, form.validate() returns true.
I don't really understand why, I read a lot that validate_on_submit() should be used, but I'm getting an error if I use it: *'ClassName' object has no attribute 'validate_on_submit'*
Here's the relevant parts of the code:
Index.py
@app.route('/contact', methods=['GET','POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All Fields are required.')
return render_template('contact.html', form=form)
else:
return 'Form posted'
elif request.method == 'GET':
return render_template('contact.html', form=form)
forms.py
from wtforms import Form, TextField, TextAreaField, SubmitField, validators,ValidationError
class ContactForm(Form):
name = TextField("Name", [validators.Required()])
email = TextField("Email")
subject = TextField("Subject")
message = TextAreaField("Message")
submit = SubmitField("Send")
contact.html
<div id="contact">
{% for message in get_flashed_messages() %}
<div class="flash">{{ message }}</div>
{% endfor %}
<form action="{{ url_for('contact') }}" method=post>
{{ form.name.label }}
{{ form.name }}
{{ form.email.label }}
{{ form.email }}
{{ form.subject.label }}
{{ form.subject }}
{{ form.message.label }}
{{ form.message }}
{{ form.submit }}
</form>
</div>
I never got the "Form posted" string even when I write something in the Name field.
Thanks in advance,
I always fail the form.validate_on_submit() when I am testing the login form following the demo code in Miguel Grinberg's book "Flask Web Development". So I think I should find a way to debug.
The debug approach I am taking is adding the code below to the app/auth/views.py:
flash(form.errors)
Then it shows me the culprit when I run to the login page:
errors={'csrf_token': ['CSRF token missing']}
So I recommend to use form.errors message to debug.