0
votes

My flask form is not getting validated.

 @admin_blueprints.route('/ManageMovies',methods=['GET', 'POST'])
 def ManageMovie():

 form = SetShowForm(request.form)

 if request.method == 'POST' and form.validate():

      print(form.movie.data)

      return redirect(url_for('admin.AdminHome'))



 engine = create_engine('mssql+pyodbc://DESKTOP-6UNRAN0/movie_f?driver=SQL Server? 
 Trusted_Connection=yes')

 form.movie.choices = [(movie.m_id, movie.m_name)for movie in (engine.execute('select * from 
 MovieMaster'))]

 form.show_time.choices = [(time.s_id, time.s_time) for time in (engine.execute('select * from 
 ShowTime'))]



 return render_template('manage_movies.html',form=form)

my template code is

 {% extends "master.html" %}


 {% block content %}

  <form method="POST">

   {{ form.hidden_tag() }}
   {{form.movie.label}}{{form.movie(class="form-control")}}
   <br>
   {{ form.show_time.label }} {{form.show_time(class="form-control")}}
   <br>
   {{form.price.label}} {{ form.price(class="form-control") }}

   <br>
   {{form.submit(class="btn btn-success")}}
   </form>



   {% endblock %}

my flask form

 class SetShowForm(FlaskForm):
       movie = SelectField('Movie Name', choices=[])
       show_time = SelectField('Set Show Time',choices=[])
       price = IntegerField('Price')

       submit = SubmitField("Set")

Once I click on my submit button, the same page gets rendered again instead of entering my (if request.method == 'POST' and form.validate():) statement and printing the data. I have no idea what is going wrong. I am filling all the fields. Are there any rule for form validation.

2
You're dynamically adding the choices to your form. You need to move this code before you try to test for validation. I.e. currently when you check for validation your form doesn't know anything about the valid choices.PGHE
I removed the (form.validate()) and just kept (request.method == POST). The code started working properly. How and is it a good practice.shaswat kumar

2 Answers

0
votes

I believe you need to use:

if form.validate_on_submit():

And you don't need to check for "POST" because validate_on_submit does that too.

0
votes

Try it

 @admin_blueprints.route('/ManageMovies',methods=['GET', 'POST'])
def ManageMovie():

form = SetShowForm()

if form.validate_on_submit():

  print(form.movie.data)

  return redirect(url_for('admin.AdminHome'))

return render_template('manage_movies.html',form=form)

And set choices values in setShowForm() directly