Flask表单提交后无重定向、无报错且数据库未更新问题求助
Hey there, let's break down what's going wrong here and fix it step by step.
Core Issues Identified
Missing CSRF Token (The Primary Culprit)
You've commented out{{ form.hidden_tag() }}in your HTML template. Flask-WTF relies on this hidden field to handle CSRF protection—without it, the form submission will never pass validation. That’s whyform.validate_on_submit()returnsFalseevery time, skipping your database commit and redirect logic entirely. Instead, the page just re-renders, and your browser ends up appending form data to the URL as a fallback.Potential Validation Failures
Even if you fix the CSRF token, invalid data in fields could still block submission. For example, your test emaildhrdoesn’t match a valid email format—if yourRegisterFormuses anEmailFieldwith theEmail()validator, this will fail validation silently unless you add error displays.
Step-by-Step Fixes
1. Restore the CSRF Token
Uncomment this line inside your <form> tag in the template—this adds the required hidden CSRF token input:
{{ form.hidden_tag() }}
This is non-negotiable for Flask-WTF form submissions to pass validation.
2. Add Error Displays to Debug
To see exactly why validation is failing, add this snippet above your form table in join.html—it will show red error messages for any invalid fields:
{% if form.errors %} <div style="color: darkred; margin-bottom: 1rem;"> {% for field, errors in form.errors.items() %} <p><strong>{{ field.replace('_', ' ') }}:</strong> {{ ', '.join(errors) }}</p> {% endfor %} </div> {% endif %}
This will tell you if a field is missing, has an invalid format, or violates any other validation rules you’ve set.
3. Validate Test Data
For testing, use valid input values:
- Use a properly formatted email like
test@example.cominstead ofdhr - Ensure all required fields (marked with * in your message) are filled in
- Stick to your date placeholder format (
dd-mm-yyyy) even though you’ve set the field to accept text
4. Confirm Database Setup
Quickly double-check that you’ve run db.create_all() (either in a Flask shell or via an initialization script) to create the Applicant table in your database. If the table doesn’t exist, db.session.commit() won’t throw an error, but no data will be saved.
Test After Fixes
Once you’ve applied these changes, submit the form again with valid data. You should be redirected to /redirected immediately, and your applicant data will appear in the database.
内容的提问来源于stack exchange,提问作者drqffhfgnx

