Hi there,
I keep encountering this error every time I try to submit a form on my Flask home.html page.
Bad Request
The CSRF session token is missing.
I’ve created 3 Flask applications that I’ve deployed on render, and 50+ GitHub commits, looked up Google and ChatGPT to not avail.
Important points to note:
- The local Flask application works perfectly fine, but not on render.com where I get the above Bad Request error.
- Every time I refresh the local app, I can see a newly generated CSRF token
- But when I refresh the Flask app on render.com, the CSRF token is always the same. Why?
- EDITED: The form only works if there is no Flask-SQLAlchemy models that connects to PostgreSQL, but my application has Flask-SQLAlchemy connected to a free tier PostgreSQL database.
I don’t see why this should be an issue though as submitting the form has no connection to the postgresql database.
Here are some snippets of my code from various files of my Flask app.
home.html page
<form method = "POST" action="{{url_for('main.home_post')}}">
<input type="hidden" id="csrf_token" name="csrf_token" value="{{csrf_token()}}">
<label for="username">username</label>
<input type="text" required id="username" name="username" placeholder="Enter username...">
<label for="email">email</label>
<input type="email" required id="email" name="email" placeholder="Enter email...">
<input type="submit" value="Submit">
</form>
<script>
var token = {{csrf_token()|tojson}};
console.log("TOKEN", token);
</script>
####### init.py file for my app
from flask import Flask
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
def create_app():
app = Flask(__name__)
csrf.init_app(app)
return app
Lastly, the backend for handling the home.html form.
@app_main.route("/", methods = ["GET", "POST"])
@app_main.route("/home", methods = ["GET", "POST"])
def home():
return render_template("home.html", title = "home")
@app_main.route("/home_post", methods = ["POST"])
def home_post():
csrf_token = session.get('_csrf_token')
print("CSRF Token (Backend):", csrf_token)
print("home post")
if request.method == "POST":
username = request.form.get("username")
email = request.form.get("email")
print("valid home post")
print(username, email)
flash("You've submitted successfully", "success")
return redirect(url_for("main.home"))
Can someone please help me with this? I’ve gone over this for several days, and I’m quite exhausted trying to resolve this.
Is this error because I’m not yet a paid plan yet and am only using the free tier?
UPDATE: I’ve bought a $25/month plan, but still have the same problem with the CSRF token not changing every time I refresh, but I can now submit a form with the CSRF missing token error, which is confusing.
Kind regards,
Michael