Reputation: 33
I am trying to create a Flask app in which you can search 'car_name' term and it will return a HTML template in which car_name is replaced with 'car_name'. form.validate_on_submit() has no errors, but when you click on the Submit button nothing happens. I have looked at similar questions, but they-re all about errors while in mine, nothing happens (no errors, but no response either). Any help would be very appreciated, thank you.
This is my main application code:
from flask_wtf import FlaskForm
from flask import Flask, flash, render_template, request, redirect
from wtforms import Form, StringField, SelectField, SubmitField
from wtforms.validators import Required
#Flask application object
app = Flask(__name__)
app.config['SECRET_KEY'] = 'jacky'
class SearchForm(FlaskForm):
motor_name = StringField("", validators=[Required()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
@app.route('/home')
def index():
form = SearchForm()
print(form.errors)
motor_name = None
if form.validate_on_submit():
motor_name = form.motor_name.data
return redirect(url_for('car', car_name=motor_name))
return render_template('homepage.html', form=form)
@app.route('/car/<car_name>', methods=['GET', 'POST'])
def car(car_name):
return render_template('carpage.html', car_name=car_name)
And this is the homepage.html code
{{ form.csrf_token }}
{{ form.protein_name.label }} {{ form.protein_name() }}
{{ form.submit() }}
Upvotes: 0
Views: 287
Reputation: 142681
I found 3 mistakes in code and I saw error messages when I ran code in console/termina/cmd.exe.
First: you used proteine_name
instead of motor_name
in template.
Second: you forgot <form method="POST"></form>
Third: you forgot to import url_for
It is strange that you didn see errors.
I used render_template_string
instead of render_template
only to easier run code with all in one file.
from flask_wtf import FlaskForm
from flask import Flask, flash, render_template, request, redirect, url_for, render_template_string
from wtforms import Form, StringField, SelectField, SubmitField
from wtforms.validators import Required
#Flask application object
app = Flask(__name__)
app.config['SECRET_KEY'] = 'jacky'
class SearchForm(FlaskForm):
motor_name = StringField("", validators=[Required()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
@app.route('/home')
def index():
form = SearchForm()
print(form.errors)
motor_name = None
if form.validate_on_submit():
motor_name = form.motor_name.data
return redirect(url_for('car', car_name=motor_name))
return render_template_string('''<form method="POST">
{{ form.csrf_token }}
{{ form.motor_name.label }} {{ form.motor_name() }}
{{ form.submit() }}
</form>''', form=form)
@app.route('/car/<car_name>', methods=['GET', 'POST'])
def car(car_name):
print('car_name:', car_name)
#return render_template('carpage.html', car_name=car_name)
return render_template_string('car_name: {{car_name }}', car_name=car_name)
app.run()
Upvotes: 1