Flask - Send POST request to specific section in the same page - python

I'm building a simple web site using flask, witch contain one page html index.html, and sections : search, about, contact. This sections are not displayed until the user enter to them
I want to send a POST request from index.html/#search to the same section : index.html/#search.
I tried to send it like that :
#app.route('/search', methods=['POST'])
def Search():
_text = request.form['text']
return render_template('index.html/#search', result=_text)
but that didn't work, and I get this error :
jinja2.exceptions.TemplateNotFound: index.html/#search
I tried to pass search as parameter :
#app.route('/search', methods=['POST'])
def Search():
_text = request.form['text']
return render_template('index.html', id="search", result=_text)
but when I run it didn't works because it takes me to http://127.0.0.1:5000/search (witch displayed the index.html page) while I want to go to http://127.0.0.1:5000/#search.
This is my index.html page:
<article id="search">
<h2 class="major">search</h2>
<form method="post" action="Search">
<label for="text">Text</label>
<input type="text" name="text" id="text" placeholder="write any thing in your mind :p" required/>
<input name="search" type="submit" value="See Polarity" class="special" />
<input type="reset" value="Reset" />
</form>
<!-- result search -->
{% if result : %}
<p>{{ result }}</p>
{% endif %}
</article>

The # represents an anchor on an existing page, not a new page.
Similarly, your syntax of :
#app.route('/search', methods=['POST'])
Would create a new route to http://127.0.0.1:5000/search . If you want it to render index.html and then jump to the search anchor you should have it render index.html as you've done it, include the _anchor attribute. It would look like:
#app.route('/', methods=['GET','POST'])
def Search():
if request.method == 'GET'
return render_template('index.html')
else:
_text = request.form['text']
return render_template('index.html', _anchor="search", result=_text)

Related

What's wrong with this Flask request? [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I have been working with flask for a long while, but after a break from it, I cant seem to figure out what's wrong here.
index.html:
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<form method="POST" action="/button">
<input class="btn" type="submit">Go</input>
</form>
main.py:
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
I'm sorry if its a simple answer but my end goal here is to load the link typed by the user, print said link, and then reload the page. What am I doing wrong?
In your index.html, your <form> tag does not include the linkHolder input.
Do the following:
<form method="POST" action="/button">
<input name="linkHolder" type="url" class="defaultTextBox advancedSearchTextBox link" placeholder="http://www.youtube.com">
<input class="btn" type="submit">Go</input>
</form>
You might also need an if statement in main.py that actually renders the page
#app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "GET":
return render_template("index.html")
if request.method == "POST":
dlink = request.form.get("linkHolder")
print(dlink)
return render_template("index.html", dlink=dlink)
You need a form with the name
Also, your tag </input> input doesn't have any closing tag you should be using button tag
<form method="POST" action="/button">
<input type="text" name="linkHolder">
<button class="btn" type="submit">Go</button>
</form>

Flask & HTML, form not Submitting

Website Link: Click Me
The "Next" button isn't submitting. My HTML Code is:
{% extends "layout.html" %}
{% block main %}
<div style='float:left;width:70%;'>
<div style='margin-top:200px;'>
<form method='POST' action='/login1'>
<input type='hidden' value="{{path}}">
<input style='width:800px;height:60px;font-size: 2em;' type='email' placeholder='Type your email to continue...' name='email' value="{{name}}">
<style>
.sub:hover{
border-style:none;
}
.sub{
border-style:none;
}
</style>
<input class='sub' type='submit' value='Next' style='height:75px;'>
</form>
</div>
</div>
<div style='float:left;width:20%;'>
<!--<img height="100%" src='static/assets/AccountBanner.png'>!-->
</div>
{% endblock %}
My Python Flask code is:
#app.route('/login')
def login():
username = request.cookies.get('login')
psw = request.cookies.get('psw')
if 'login' in request.args.get('path'):
return redirect('/login?path=/')
if username == None:
return render_template('login/index.html',path = request.args['path'])
with open('static/json/members.json') as a:
a = json.load(a)
found = False
for i in a:
if i["email"] == username:
if str(i["password"]) != str(psw):
return redirect('/')
else:
found = True
if found == False:
return render_template('login/index.html',path=request.args['path'])
return redirect('/')
#app.route('/login1', methods=['POST'])
def main1():
return render_template('password.html',redirect1 = "/login1"+request.args['path'])
What I am trying to do is asking the user for his/her email and then render a page asking for a password. However, the submit button isn't working. I am using action and method=POST submit.
Ok, I know why it didn't work.
Everytime I make an error (syntax error) OR I POST to a 404 page, I have a 404 and 500 function where it makes you login before viewing the 404/500 page. That's why it kept on redirecting to the original login page. It works now.

Flask, why does request.form runs error 400?

I am trying to extract text from the following HTML code:
#app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
H_desiderata = float(request.form.get('H_desiderata')) #THIS CAUSES THE ERROR
return render_template('form1.html')
HTML below:
<body>
<h2>Brioche Recipe</h2>
<form>
<div class="grid-container">
<div class="grid-item">
<label class="text" for="H_desiderata">
H_desiderata:
</label><be>
<input type="number" id="H_desiderata" name="H_desiderata1"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
Before putting it into a grid it worked:
old working code:
<form>
<label for="H_desiderata">H_desiderata:</label><br>
<input type="number" id="H_desiderata" name="H_desiderata"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
How should I adapt request.form to return the value within the input box?
There is so much wrong with your code, but let's start with this:
request.form is empty when request.method == "GET. So. request.form['H_desiderata'] will give a key error.
Move that to the POST section of your view. Also, use request.form.get('H_desiderata', -9999999) in case it's not defined.
UPDATE:
OK, now try:
if request.method == 'POST':
print(request.form)
print(request.form.get('H_desiderata'))
print(float(request.form.get('H_desiderata')))
H_desiderata = float(request.form.get('H_desiderata'))
Then, you are going to want:
return render_template('form1.html', val_H_desiderata=H_desiderata)
UPDATE2:
Your <form> tag is malformed. Try:
<form action="/" method="post">
UPDATE3:
You change the name of the input, so change to: request.form.get('H_desiderata1')

Employing Post Method in Flask

Using the following:
from flask import Flask, render_template
import beautiful_soup_tidal
app = Flask(__name__)
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/richmond', methods=['POST'])
def richmond():
someTides = beautiful_soup_tidal.getTides()
return render_template('richmond.html',someTides=someTides)
if __name__ == "__main__":
app.run(debug=True)
And attempting to render the following (richmond.html):
<div id="content" class="form-group">
<form method="post" action="/richmond">
<label style="vertical-align: middle;">channel depth at mean low water
<input type="number" step="0.1" value = "34.5" name="channelDepth"/>FEET</label><br><br>
<label style="vertical-align: middle;">required underkeel clearance
<input type="number" step="0.1" value = "2" name="underkeelClearance"/>FEET</label><br><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
I get the following error: 'The method is not allowed for the requested URL.'
If I delete ', methods=['POST']' in the first section the template renders.
The question: How do I render the template successfully using the post method?
i believe this line should also include GET so that you can render the html form first time round before you actually click submit to post it.
#app.route('/richmond', methods=['POST'])
so it would change to
#app.route('/richmond', methods=['GET', 'POST'])

flask - url with searched word

I want to ask how to make my urls to include the worh that I searched. Something like this:
http://host/filter?test
My code:
#app.route('/filter', methods=['POST', 'GET'])
def filter():
if request.method == 'POST':
if str(request.form['search_string']) <> '':
api.queryMessage(request.form['search_string'])
return render_template('main.html', search_string=search_string)
And my template, main.html:
<form name="filters" action="{{ url_for('filter') }}" method=post id="filters">
<div style="position: absolute; top:100px; left:300px">
<p>Search string: <input type=text size=80 title="Match all of the words" name=search_string value="{{search_string}}"></p>
<input type=submit value=Filter/Search onclick=loopSelected();>
<input type="hidden" name="chosen" id="chosen" value="{{chosen}}" />
</div>
</form>
You're now using POST request. Use GET request, so browser will put your form values to URL.
in HTML form set method="GET":
<form name="filters" action="{{ url_for('filter') }}" method="GET" id="filters">
You'll get URL in the following form:
http://host/filter?search_string=test&chosen=<id>&<some other trash>
In Flask use request.args instead of request.form:
if request.method == 'GET':
if request.args.get('search_string'):
...

Categories

Resources