Flask form not validating with HTML [duplicate] - python

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Form is never valid with WTForms
(1 answer)
Closed 2 years ago.
I've tried looking through the documentation and other posts on here, though I'm still having trouble.
views.py
#bp.route('/')
def index():
return render_template("index.html")
#bp.route('/newSearch', methods=['GET', 'POST'])
def newSearch():
form = NewSearchForm()
if form.validate_on_submit():
# DB code
return redirect(url_for('newPage.html'))
return render_template('newSearch.html', form=form)
Once the user enters a search query and clicks "submit" it should redirect to the results page. However, It's not validating the form correctly with my current form tag.
index.html
<form action="{{ url_for('newSearch') }}" enctype="multipart/form-data" method="post">
<input class="btn btn-primary" type="submit" value="Search"></input>
</form
The button lives in the index.html. It fails to redirect to newPage.html in the case above. What is missing that's causing it to fail validation? any help would be greatly appreciated!

Related

Flask Post Error 500 (Internal Server Error) [duplicate]

This question already has answers here:
How to debug a Flask app
(14 answers)
Flask application traceback doesn't show up in server log
(4 answers)
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 4 years ago.
I have a simple form that asks the user to input an email. My goal is to send that email back into Python so that I can append it to a text file.
HTML:
<form method="post" target="frame">
<input name="email" value="{{request.form.text}}" id="email">
<input type="submit" value="Sign Up">
</form>
Flask:
#app.route('/', methods=['GET', 'POST'])
def my_form():
if request.method == "POST":
inputed_email = request.form.get('email')
return inputed_email
return render_template("my-form.html")
Whenever I enter an email into the form, I get this error:
What is preventing the form data from being sent back into Python? Any help is appreciated. Thank you!

Why does html POST take me to an unexpected page?

I have a simple web application built with Python using flask that has three pages: main, index, and post. I am trying to get to the "if request.method == "POST"" section of the index page. To test this I've asked it to render the post.html page. For some reason when I send a POST method from the index page I'm instead being redirected to my main_page. The python code looks like this:
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["DEBUG"] = True
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main_page.html")
#implied ELSE here (if it's not GET, do the following for a POST)
return redirect(url_for('index'))
#app.route('/index', methods=['GET', 'POST'])
def new_index():
if request.method == "POST":
#I AM TRYING TO GET HERE
return render_template('post.html')
if request.method == "GET":
return render_template('index.html',)
#app.route('/post')
def post():
return render_template('post.html')
The POST method from index.html comes from this:
<div class="row">
<form role="form" method='POST' action='.'>
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
I'm not particularly familiar with HTML but I've tried everything I can think of. Any advice?
When you want to link to the same page in a form action you should actually put a question mark, an empty string, a hash or just leave out the attribute all together. Doing either of these will fix your code.
<form role="form" method='POST' action='?'>
<form role="form" method='POST' action='#'>
<form role="form" method='POST' action=''>
<form role="form" method='POST'>
My personal preference is using.
<form role="form" method='POST' action='#'>
This will validate in XHTML and doesn't open up any known attack vectors.
First thing I did was testing your API using Postman, and that all works fine: GET goes to the GET handler, POST goes to the POST handler.
The error I found is in the html form, in particular the action tag: you should point that to the API handler explicitly, and relative to the hostname. So, for example, setting that to:
<form role="form" method='POST' action='/index'>
will actually perform a POST on the /index API of your Flask app.

Can't use PUT method with flask [duplicate]

This question already has answers here:
Using PUT method in HTML form
(10 answers)
Closed 6 years ago.
I wrote this easy program:
#app.route('/puttest/', methods=['GET', 'PUT'])
def upload_file():
if request.method == 'PUT':
return 'Hello, {}!'.format(request.form['name'])
else:
return '''
<title>Does it work ?</title>
<h1>PUT test</h1>
<form action=http://localhost:8887/puttest/ method=put>
<input type=text name=name>
<input type=submit value=try>
</form>
'''
if __name__ == '__main__':
app.run('0.0.0.0', 8887)
It works perfectly for GET method, but it doesn't work with PUT. Trying to send put message, I can see this error at a browser:
Method Not Allowed
The method is not allowed for the requested URL.
What has happened to put method ?
It will work fine if I change put method on post everywhere in program.
PUT won't work with HTML method attribute.
Allowed values are: method = get|post
You have to use POST in Webforms:
#app.route('/puttest/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
return 'Hello, {}!'.format(request.form['name'])
else:
return '''
<title>Does it work ?</title>
<h1>PUT test</h1>
<form action=http://localhost:8887/puttest/ method=post>
<input type=text name=name>
<input type=submit value=try>
</form>
'''
Further informations at: Using PUT method in HTML form and HTML Standard

Retrieve text from textarea in Flask [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I would like to be able to write a multi-line text in a textarea (HTML), and retrieve this text in python for processing using Flask. Alternatively, I would like to be able to write a multi-line text in a form. I have no clue on using JS, so that won't help me.
How am I to go about doing that?
Render a template with the form and textarea. Use url_for to point the form at the view that will handle the data. Access the data from request.form.
templates/form.html:
<form action="{{ url_for('submit') }}" method="post">
<textarea name="text"></textarea>
<input type="submit">
</form>
app.py:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/submit', methods=['POST'])
def submit():
return 'You entered: {}'.format(request.form['text'])

Python Flask html form not displaying - GET instead of POST method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to learn python and some of the Python web frameworks. Currently I'm following following a Flask course, but have run into a problem with an html form that I cannot find a solution to.
The code below is supposed to create a very simple page at '/' where the user can log in using an html form and is redirected to /main upon successful login.
However instead of display the html form, the page immediately redirects to /main.
At least part of the problem seems to be that request.method is returning GET, rather than POST, since when I add flash(request.method), GET is returned.
I've checked the code multiple times and it is exactly the same as the tutorial I'm following, but the result is not the same.
I'm using python 3.5 and I believe Flask version 0.10.1.
This is my main python file:
from flask import Flask, render_template, request, session, \
flash, redirect, url_for, g
import sqlite3
# configuration
DATABASE = 'blog.db'
USERNAME = 'admin'
PASSWORD = 'admin'
SECRET_KEY = 'hard_to_guess'
app = Flask(__name__)
# pulls in app configuration by looking for UPPERCASE variables
app.config.from_object(__name__)
# function used for connecting to the database
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
#app.route('/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME'] or\
request.form['password'] != app.config['PASSWORD']:
error = 'Invalid credentials. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('main'))
return render_template('login.html', error=error)
#app.route('/main')
def main():
return render_template('main.html')
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
And here is the login.html code:
{% extends "template.html" %}
{% block content %}
<h2>Welcome to the Flask Blog!</h2>
<h3>Please login to access your blog.</h3>
<form action="" method="post">
Username: <input type="text" name="username" value="{{ request.form.username }}">
Password: <input type="password" name="password" value="{{ request.form.password }}">
<p><input type="submit" value="Login"></p>
</form>
{% endblock %}
Any help or suggestions would be very much appreciated.
It looks like your indentation levels are off of the if ...then ...else block in your request.method == 'POST' logic. Indent your else block to match up and give it a try.

Categories