flask - url with searched word - python

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'):
...

Related

Use flask to get an image uploaded on a html form

I am new to flask and i am using google colab to do some basic flask stuff.
I have a html-form:
<!DOCTYPE html>
<html>
<body>
<h1>The input accept attribute</h1>
<form action="#" method="post">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" enctype="multipart/form-data" accept="image/*">
<input type="submit" value="submit">
</form>
</body>
</html>
Then i have FLASK code as to get the uploaded image:
#app.route("/test", methods=['POST','GET'])
def test_page():
if request.method == "POST":
image = request.files.get('img', '')
image = request.form["img"]
print("img ",image)
return "<h1> yo! </h1>"
else:
return render_template('index.html')
DEBUGGING RESULTS:
#debug
print('request.method', request.method)
print('request.args', request.args)
print('request.form', request.form)
print('request.files', request.files)
request.method POST
request.args ImmutableMultiDict([])
request.form ImmutableMultiDict([('img', 'cat.jpg')])
request.files ImmutableMultiDict([])
The problem is i want to doo some processing on the uploaded image but request.files return nothing and request.form just gives me the name. Please any help will be appreciated.
The enctype attribute should be defined within the form tag, not within the input element. Here, the formatting of the data is defined when the form is transmitted.
This could fix the problem.
<form method="post" enctype="multipart/form-data">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit" value="submit">
</form>

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')

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

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)

Django, Getting a value from a POST

I have in my template:
This is passed by {{form}}
<form action="" method="POST">
Inicio: <input type="text" id="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Then in the views.py
def test(request):
if request.method != 'POST':
context = {'form': 'by GET'}
return render(request, 'test.html', context)
else:
if 'start' in request.POST:
start = request.POST['start']
else:
start = False
context = {'form': start}
return render(request, 'test.html', context)
It seems that always return False
If I dont check the existance of the key I have this error:
MultiValueDictKeyError
And the erropage says : "'start'" (single plus double quotes)
id is intended for javascript and css purposes. For variables that are important on server side, you should use name tag.
<input type="text" id="start" name="start">
You need to add a name attribute in your input, so when you are getting the POST data it will be found.
<form action="" method="POST">
Inicio: <input type="text" id="start" name="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Also I recommend you to do the following change in your view:
Replace
request.POST['start']
by:
request.POST.get('start')
So, if the field is not found, it will be reassigned whith a None value.
add name
<input type="text" name="start" id="start">

flask-wtf behavior with 2 forms in view

example 2 forms in one page:
<form name="form_A" class="form-inline" action="/" method="post">
{{form_A.hidden_tag()}}
{{form_A.name(type="text", class="form-control")}}
<input type="submit" name="form_A" id="form_A" class="btn btn-sm btn-success" value="FORM_A">
</form>
<form name="form_B" class="form-inline" action="/" method="post">
{{form_B.hidden_tag()}}
{{form_B.name(type="text", class="form-control")}}
<input type="submit" name="form_A" id="form_A" class="btn btn-sm btn-success" value="FORM_B">
</form>
and router:
#app.route('/', methods = ['GET', 'POST'])
def index():
form_A = ExampleForm1(request.form)
form_B = ExampleForm1(request.form)
if form_A.validate_on_submit():
...
if form_B.validate_on_submit():
...
any submit button (FORM_A or B) call form_A.validate_on_submit() and form_B.validate_on_submit() together(!). why?
and how to submit only one form in this case?
EDIT:
i solve this problem just add check data any field and use is_submitted method:
if form_A.is_submittied() and form_A.name.data:
...
When using more than one form, you need to give each form a prefix:
form_A = ExampleForm1(request.form, prefix='form_a')
form_B = ExampleForm1(request.form, prefix='form_b')

Categories

Resources