Modal forms not displaying - python

i am working on a project, and i created two modal forms on the landing page. both forms are for registration and login.
only one form seems to be coming up and the other cannot come up and thereby making it impossible for the forms to submit.
how do i achieve this challenge, that both forms can be displayed and can submit to the database respectively.
also i am a rookie i just started a few weeks ago
i have tried and all i keep getting are errors or only one form displays
#app.route('/main', methods=['GET', 'POST'])
def main():
form = Signup_Form()
forms = Login_Form()
if request.method =="GET":
return render_template('/main.html', form=form, forms=forms)
if request.method == "POST":
return render_template('main.html', form=form, forms=forms)
else:
return redirect('home.html')
i expect to see both forms display when clicked and also submit to the database when the submit button is clicked

Related

How can I execute defined form validators from HTML before submitting?

I have a defined form created using FlaskForm/WTForms where I also defined the validators of the same form. I would like to know how can I validate it using the validators already defined in my form before submitting it, for example, having one button to validate the form and then another to submit the form.
I'm assuming I need to find a way to execute form.validate() from the html when a button is clicked. My approach was to create a view to only execute form.validate() and call it when a button is clicked using jQuery. However, this is not working. And I'm assuming because the form object created in the "create" view and that is passed to the HTML is not the same as the form object created in the "_validate_form" view. But I don't know what other approaches to take. I would appreciate some ideas on how could I solve this problem.
This is my FlaskForm:
class CreateTripForm(FlaskForm):
truck = SelectField('Truck', widget=CustomSelect(), validators=[selection_required], validate_choice=False)
origin = SelectField('Origin',
widget=CustomSelect(),
validators=[selection_required], validate_choice=False)
material = SelectField('Material',
widget=CustomSelect(),
validators=[selection_required], validate_choice=False)
destination = SelectField('Destination',
widget=CustomSelect(),
validators=[selection_required], validate_choice=False)
sender_comment = TextAreaField('Comment', validators=[validators.Length(max=150, message="Máximo 150 caracteres!")])
submit = SubmitField('Confirm Trip')
This is my view when form.validate_on_submit():
#trips_blueprint.route('/create', methods=['GET', 'POST'])
#login_required
def create():
form = f.CreateTripForm()
if form.validate_on_submit():
trip_dict = {
'truck_id': form.truck.data,
'material_name': form.material.data,
'origin_name': form.origin.data,
'destination_name': form.destination.data,
'sender_username': current_user.username,
'sender_comment': form.sender_comment.data
}
trip = Trip.create(**trip_dict)
return redirect(url_for('trips.create'))
return render_template('create_home.html', form=form)
This is my view to only validate form. Which is not working.
#trips_blueprint.route('/_validate_form', methods=['POST'])
def _validate_form():
print('In _validate_form!')
form = f.CreateTripForm()
if form.validate():
return jsonify(True)
This is the jQuery script I'm using to try to validate the form:
function validateForm(){
$.post( "{{url_for('trips._validate_form') }}" );
}
$('#validation_button').click(function(){
validateForm();
});

Multiple Forms on 1 Page Python FLASK

So I am loading all users from a database on a single page and I'm generating a password reset form for each user on the same page rather than having an individual page for each user.
My question is how can I click submit and apply the change for that specific user since I have multiple forms and submit buttons for each user via drop-down menu?
In my case the submit button is the "Reset Password" button.
I'm trying to call the form normally using
if request.method == "POST" and form.validate():
password = request.form['password']
but I'm getting exception error
name 'form' is not defined
I've been trying to solve this for a while but i'm getting pretty confused now as I've got multiple forms (one per user) on the same page.
NOTE : I'm not using WTForms for this task
Thanks
I'm not sure if this one has been answered but here is what i just figured out:
After your standard
if request.method == 'POST':
you can test for the existence of each form item within the request.form data. So add another if statement after the first
if 'my_form_element_name' in request.form:
print ('stuff')
If you have other types of form data such as files, you can do something like:
if request.method == 'POST':
if 'file_element_name' in request.files:
return stuff
elif 'my_form_element_name' in request.form:
return stuff
else: return stuff
else: return stuff
I have four forms in one html file and this method worked for me.

Python/Flask. How can include multiple forms on a single view.py file

I am developing a python web application using the Flask framework. The application has several forms namely: The login form, the registration form, check balance form, withdraw cash form, and transfer money form. I have a single view.py file that i intend to use to render all these forms like this:
###login form
#app.route('/login', methods = ['POST'])
def login():
form = LoginForm()
if request.method == 'POST':
if form.validate() == False:
flash('pin is required.')
else:
return render_template('index.html')
elif request.method == 'GET':
return render_template('login.html', form = form)
##withdraw cash
#app.route('/withdrawCash', methods=['GET', 'POST'])
def withdrawCash():
form = withdrawCashForm()
if request.method == 'POST':...
##transfer cash
#app.route('/transferCash', methods=['GET', 'POST'])
def transferCash():
form = transferCashForm()
if request.method == 'POST':......etc
Is this possible to have one view file rendering all these forms or should i have view files for each form?
The question above has been edited. I initially thought i had gone around the problem but after reviewing the problem it is clear that whatever answer i had provided was wrong.

Redirect to other view after submitting form

I have a survey form. After submitting the form, I'd like to handle saving the data then redirect to a "success" view. I'm using the following code right now, but it just stays on the current url, while I'd like to go to /success. How can I do this?
#app.route('/surveytest', methods=['GET', 'POST'])
def surveytest():
if request.method == 'GET':
return render_template('test.html', title='Survey Test', year=datetime.now().year, message='This is the survey page.')
elif request.method == 'POST':
name = request.form['name']
address = request.form['address']
phone = request.form['phone']
email = request.form['email']
company = request.form['company']
return render_template('success.html', name=name, address=address, phone = phone, email = email, company = company)
You have the right goal: it's good to redirect after handling form data. Rather than returning render_template again, use redirect instead.
from flask import redirect, url_for, survey_id
#app.route('/success/<int:result_id>')
def success(result_id):
# replace this with a query from whatever database you're using
result = get_result_from_database(result_id)
# access the result in the tempalte, for example {{ result.name }}
return render_template('success.html', result=result)
#app.route('/survey', methods=["GET", "POST"])
def survey():
if request.method == 'POST':
# replace this with an insert into whatever database you're using
result = store_result_in_database(request.args)
return redirect(url_for('success', result_id=result.id))
# don't need to test request.method == 'GET'
return render_template('survey.html')
The redirect will be handled by the user's browser, and the new page at the new url will be loaded, rather than rendering a different template at the same url.
Though I am not specifically answering your current question I found myself with a similar problem with getting the page to redirect after the submission button had been clicked. So I hope this solution could potentially work for others that find themselevs in a similar predicament.
This example uses Flask forms for handling forms and submissions.
from flast_wtf import FlaskForm
#app.route("/", methods=["GET", "POST"])
def home():
stock_form = StockForm()
tick = stock_form.text_field.data
if tick != None:
return redirect(f'/{tick}', code=302)
return render_template("home.html", template_form=stock_form, ticker=tick)
The if statement checks that the submission after being clicked has a value, then redirects to your chosen link. This code is a copy and paste from a badly programmed stock price lookup.

Why will WTForms submit again when I refresh the page?

I created the following form:
class ContentForm(Form):
content = StringField(u'write here' , validators=[Required()])
submit = SubmitField(u'Let them know' )
When I submit, things seem to work. However, when I refresh the page afterwards, the form is submitted again. How do I fix this?
You need to redirect after making a POST request. Otherwise, the browser will do what you're experiencing (the behavior has nothing to do with WTForms).
#app.route('/my_form', methods=['GET', 'POST']
def my_form():
form = ContentForm()
if form.validate_on_submit():
# do stuff
return redirect('my_form') # or wherever
return render_template('my_form.html', form=form)

Categories