Clear valid form after it is submitted - python

I want to reset the form after it validates. Currently the form will still show the previous data after it is submitted and valid. Basically, I want the form to go back to the original state with all fields clean. What is the correct to do this?
#mod.route('/', methods=['GET', 'POST'])
def home():
form = NewRegistration()
if form.validate_on_submit():
#save in db
flash(gettext(u'Thanks for the registration.'))
return render_template("users/registration.html", form=form)

The issue is that you're always rendering the form with whatever data was passed in, even if that data validated and was handled. In addition, the browser stores the state of the last request, so if you refresh the page at this point the browser will re-submit the form.
After handling a successful form request, redirect to the page to get a fresh state.
#app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
# do stuff with valid form
# then redirect to "end" the form
return redirect(url_for('register'))
# initial get or form didn't validate
return render_template('register.html', form=form)

davidism answer is correct.
But once I had to reload a form with only a few fields that had to be resetted.
So, I did this, maybe it's not the cleanest way but it worked for me:
form = MyForm()
if form.validate_on_submit():
# save all my data...
myvar1 = form.field1.data
myvar2 = form.field2.data
# etc...
# at first GET and at every reload, this is what gets executed:
form.field1.data = "" # this is the field that must be empty at reload
form.field2.data = someobject # this is a field that must be filled with some value that I know
return render_template('mypage.html', form=form)

You can clear a form by passing formdata=None
#mod.route('/', methods=['GET', 'POST'])
def home():
form = NewRegistration()
if form.validate_on_submit():
#save in db
######### Recreate form with no data #######
form = NewRegistration(formdata=None)
flash(gettext(u'Thanks for the registration.'))
return render_template("users/registration.html", form=form)

you can also return new form object using render_template if form does not validates you can also pass message
#mod.route('/', methods=['GET', 'POST'])
def home():
form = NewRegistration()
if form.validate_on_submit():
#save in db
return render_template("user/registration.html", form = NewRegistration())
return render_template("users/registration.html", form=form)

Related

Collect information from first app route and submit that information in a different app route

I have two app routes in my flask app, the first collects customer data and then submits it to the database.
The second collects address data then submits it to the database.
#app.route ('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
customer_details = Customer(first_name=form.first_name.data, last_name=form.last_name.data, email_address=form.email_address.data)
db.session.add(customer_details)
db.session.commit()
return redirect(url_for('register_address'))
return render_template('register.html', title='Personal Details', form=form)
#app.route('/register_address', methods=['GET', 'POST'])
def register_address():
form = AddressForm()
if form.validate_on_submit():
address_details = Address(house_no=form.house_no.data, first_line=form.first_line.data, second_line=form.second_line.data, postcode=form.postcode.data)
db.session.add(address_details)
db.session.commit()
flash(f'Account created successfully')
return redirect(url_for('home'))
return render_template('register_address.html', title='Address Details', form=form)
In the register_address function I would like to submit all the database actions but I am not 100% sure how to do this.
Any pointers on this would be good a idea.
Cheers.

Flask-wtforms Redirect on Form Submission and Pass Variables

I am struggling to figure out why I am unable to pass variables to my redirected url. I have attempted the suggestions in the following questions, but for some reason they are not working.
redirect while passing arguments
How can I pass arguments into redirect(url_for()) of Flask?
The only thing I can think of is that it is because I am using flask-wtforms to validate the form before the redirect. I haven't seen much in way of answers/suggestions for this scenario. So here I am.
#app.route('/quiz/', methods=['GET', 'POST'])
def quiz():
form = Quiz()
if form.validate_on_submit():
q1_answer = 'North'
return redirect(url_for('result', q1_answer=q1_answer))
return render_template('quiz.html', form=form)
#app.route('/result/', methods=['GET', 'POST'])
def result():
q1_correct_answer = request.args.get('q1_answer')
return render_template('result.html', q1_correct_answer=q1_correct_answer)
The redirect works the way it should. The 'result' url and its corresponding template are rendered. I just can't get the variable (q1_answer) to pass. My template always returns a value of None. Any help would be greatly appreciated.
I think you use it
#app.route('/quiz/', methods=['GET', 'POST'])
def quiz():
form = Quiz()
if request.method == "POST" and form.validate_on_submit():
q1_answer = 'North'
return redirect(url_for('result', q1_answer=q1_answer))
return render_template('quiz.html', form=form)
#app.route('/result/', methods=['GET', 'POST'])
def result(q1_answer):
return render_template('result.html', q1_correct_answer=q1_answer)

How to rewrite this Flask view function to follow the post/redirect/get pattern?

I have a small log browser. It retrieves and displays a list of previously logged records depending on user's input. It does not update anything.
The code is very simple and is working fine. This is a simplified version:
#app.route('/log', methods=['GET', 'POST'])
def log():
form = LogForm()
if form.validate_on_submit():
args = parse(form)
return render_template('log.html', form=form, log=getlog(*args))
return render_template('log.html', form=form)
However it does not follow the post/redirect/get pattern and I want to fix this.
Where should I store the posted data (i.e. the args) between post and get? What is the standard or recommended approach? Should I set a cookie? Should I use flask.session object, create a cache there? Could you please point me in the right direction? Most of the time I'm writing backends...
UPDATE:
I'm posting the resulting code.
#app.route('/log', methods=['POST'])
def log_post():
form = LogForm()
if form.validate_on_submit():
session['logformdata'] = form.data
return redirect(url_for('log'))
# either flash errors here or display them in the template
return render_template('log.html', form=form)
#app.route('/log', methods=['GET'])
def log():
try:
formdata = session.pop('logformdata')
except KeyError:
return render_template('log.html', form=LogForm())
args = parse(formdata)
log = getlog(args)
return render_template('log.html', form=LogForm(data=formdata), log=log)
So, ultimately the post/redirect/get pattern protects against submitting form data more than once. Since your POST here is not actually making any database changes the approach you're using seems fine. Typically in the pattern the POST makes a change to underlying data structure (e.g. UPDATE/INSERT/DELETE), then on the redirect you query the updated data (SELECT) so typically you don't need to "store" anything in between the redirect and get.
With all the being said my approach for this would be to use the Flask session object, which is a cookie that Flask manages for you. You could do something like this:
#app.route('/log', methods=['GET', 'POST'])
def log():
form = LogForm()
if form.validate_on_submit():
args = parse(form)
session['log'] = getlog(*args)
return redirect(url_for('log'))
saved = session.pop('log', None)
return render_template('log.html', form=form, log=saved)
Also, to use session, you must have a secret_key set as part of you application configuration.
Flask Session API
UPDATE 1/9/16
Per ThiefMaster's comment, re-arranged the order of logic here to allow use of WTForms validation methods for invalid form submissions so invalid form submissions are not lost.
The common way to do P/R/G in Flask is this:
#app.route('/log', methods=('GET', 'POST'))
def log():
form = LogForm()
if form.validate_on_submit():
# process the form data
# you can flash() a message here or add something to the session
return redirect(url_for('log'))
# this code is reached when the form was not submitted or failed to validate
# if you add something to the session in case of successful submission, try
# popping it here and pass it to the template
return render_template('log.html', form=form)
By staying on the POSTed page in case the form failed to validate WTForms prefills the fields with the data entered by the user and you can show the errors of each field during form rendering (usually people write some Jinja macros to render a WTForm easily)

Passing data into flask template

During login form validation, I query for a user and store the object on the form instance. I want to pass the user object into the template. Following Python, Flask - Passing Arguments Into redirect(url_for()) , I tried:
def home():
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or url_for("user.profile")
return redirect(redirect_url, userobj=form.user)
I'm redirecting to :
#blueprint.route("/profile")
#login_required
def profile():
return render_extensions("users/profile.html")
and again I want to pass the user object into profile.html template.
I'm getting:
TypeError: redirect() got an unexpected keyword argument 'userobj'
How can I fix this?
You may not be doing it correct. user which is logged in is available through current_user which is available in from flask.ext.login import current_user
this is how i did
#auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password')
return render_template('auth/login.html', form=form)
in the index view i am able to access it like current_user.username same in the template
try this it may help
peace

How to pass a "WTF object" in Flask

I am using flask to develop a website and now i encountered a problem.
I am thinking whether I can pass a "WTF form" object in flask.
Like,
#app.route('/')
#app.route('/index')
#login_required
def index():
user = flask.g.user
form = PostForm()
return flask.render_template("index.html",
title="Home",
user=user,
form = form)
This form, an instance of PostForm, actually will be processed by the following code:
#app.route('/note/<int:id>', methods=['POST'])
def note(id):
form = ?(how to get this form?)?
if form.validate_on_submit():
print id
content = form.body.data
currentTime = time.strftime('%Y-%m-%d', time.localtime(time.time()) )
user_id = id
return flask.redirect(flask.url_for('login'))
return flask.redirect( flask.request.args.get('next') or
flask.url_for('index') )
In the template, I set the action to be "/note/1", so it will forward to this address. But the question, how can I get the form created in the function index?
I have tried to use flask.g (Obviously, it does not work because it's another request). And I also tried to use global variable. It failed, either.
Could anyone give me a solution or any advice?
Thank you in advance!
You simply need to construct a new version of PostForm in your note route and use the posted data in request.form:
from flask import request
#app.route('/note/<int:id>', methods=['POST'])
def note(id):
form = PostForm(request.form)
# or, if you are using Flask-WTF
# you can do
# form = PostForm()
# and Flask-WTF will automatically pull from request.form

Categories

Resources