how to create a dynamic url from form using flask - python

I have a form on my home page that is generated from a list of folders on disk. I can't figure out how to route to the next page and add a dynamic url. So that the url reads http://127.0.0.1:5000/projects/
(http://127.0.0.1:5000/projects/banana)
(http://127.0.0.1:5000/projects/apple)
#app.route("/")
def home():
return render_template("home.html", list_projects=list_projects)
#app.route('/', methods=['POST', 'GET'])
def project_select_form():
project_select = request.form['project']
return redirect(url_for("project_page"), project=project_select)
#app.route('/projects/<project>', methods=['POST', 'GET'])
def project_page(project):
return render_template("project_selected.html", project=project)
if __name__ == "__main__":
html
<form method = "POST">
<select id="project" name="project">
{% for x in list_projects %}
<option value="{{ x }}">{{ x }}</option>
{% endfor %}
</select>
<input name="text" type="submit">
</form>

All you need to do is, add a JavaScript/jQuery function that will call the URL.
<form method="GET">
<select id="project" name="project">
<option value="a1">a1</option>
<option value="b1">b1</option>
</select>
<input type="button" value="Submit" onclick="myFunction()">
</form>
With this slight modification in your form, you can now have a function like this:
<script>
function myFunction() {
var e = document.getElementById("project");
var list_project = e.options[e.selectedIndex].value;
var theUrl = "http://127.0.0.1:5000/project/".concat(list_project);
window.location.replace(theUrl);
}
</script>
This simply calls the URL, which in turn renders the project_selected.html.
Hope this helps. Good luck.

The answer was to add an if statement to the form. Otherwise it errors out
#app.route("/", methods=['POST', 'GET'])
def home():
if request.form:
project_select = request.form['project']
return redirect(url_for("project_page", project=project_select))
else:
return render_template("home.html", list_projects=list_projects)

Related

action after button click in scroll menu in html with using Flask

I have array of two elements in flask:
from flask import Flask, render_template
import psycopg2
import numpy as np
app = Flask(__name__)
d = [10,12,16,17]
#app.route('/about')
def about():
return render_template('about.html', d=d, length=len(d))
if __name__ == '__main__':
app.run()
And also I have Vertical Scroll Menu in html:
<h1>Vertical Scroll Menu</h1>
<div class="vertical-menu">
change number
{% for i in range(length) %}
select number{{d[i]}}
{% endfor %}
</div>
<input type="text" name="name" required="required">
I need to insert number in array into output form after href clicking.How should I solve my problem?
Demo HTML
<form action="{{url_for('process_number')}}" method="POST">
<select name="number">
{% for i in d %}
<option value="{{d[i]}}">{{d[i]}}</option>
{% endfor %}
</select>
<input type="submit"/>
</form>
Flask function
#app.route('/process-number', methods=['GET', 'POST'])
def process_number():
if request.method == 'POST':
selected_number = request.form['number']
# do what you want

Flask Application Showing 404 on Post

This is my first attempt at deploying a machine learning application and also my first time using flask. Essentially the user will fill out a form on an html page and the input from the form will be used as input to the machine learning model which is saved in a pickle file, model.pkl in the code below. I am running into one snag that I can't seem to break past..
Every time I submit from index.html and post to result.html I'm receiving a 404 error.
script.py:
#importing libraries
import os
import numpy as np
import flask
import pickle
from flask import Flask, render_template, request
app=Flask(__name__)
#app.route('/')
#app.route('/index')
def index():
return flask.render_template('index.html')
def ValuePredictor(to_predict_list):
to_predict = np.array(to_predict_list).reshape(1,12)
loaded_model = pickle.load(open("model.pkl","rb"))
result = loaded_model.predict(to_predict)
return result[0]
#app.route('/result',methods = ['POST'])
def result():
if request.method == 'POST':
to_predict_list = request.form.to_dict()
to_predict_list=list(to_predict_list.values())
to_predict_list = list(map(int, to_predict_list))
result = ValuePredictor(to_predict_list)
if int(result)==1:
prediction='Income more than 50K'
else:
prediction='Income less that 50K'
return render_template("result.html",prediction=prediction)
index.html:
<html>
<body>
<h3>Income Prediction Form</h3>
<div>
<form action="/result.html" method="POST">
<label for="age">Age</label>
<input type="text" id="age" name="age">
<br>
<label for="edu">Education</label>
<select id="edu" name="edu">
<option value="0">High School</option>
<option value="1">College Degree</option>
</select>
<br>
<label for="martial_stat">Marital Status</label>
<select id="martial_stat" name="martial_stat">
<option value="0">not married</option>
<option value="1">married</option>
</select>
<br>
<label for="gender">Gender</label>
<select id="gender" name="gender">
<option value="0">Female</option>
<option value="1">Male</option>
</select>
<br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
result.html:
<html>
<body>
<h1> {{ prediction }}</h1>
</body>
</html>
I can't seem to figure this out. My code never seems to reach the first line in the result() function. As soon as I submit from index.html http://127.0.0.1:5000/result.html throws a 404 error. Any suggestions?
The error is very simple here, the action property in index.html should just be
<form action="/result" method="POST">
instead of
<form action="/result.html" method="POST">
You want to use /result to go through your flask function. Hope this helps!
You are posting to the endpoint /result.html:
<form action="/result.html" method="POST">
... but your route in flask is defined as /result (with no .html):
#app.route('/result',methods = ['POST'])
def result():
...
These two need to match, so consider changing the route to result.html.
Instead of <form action="/result.html" method="POST">
Can Use <form action="{{ url_for('result') }}" method="POST">

How to get html from input and save as variable in Python Django

I'm trying to get a simple input (which would be an integer) from the user, and use it as a variable in the next python function. But whenever I try to print the input it returns None.
Here's my code:
HTML
<form action="/./" method="POST">{% csrf_token %}
<input type="text" name="quantity" placeholder="Repeat" size=2>
<input type="submit" value="Save!">
</form>
Python Django (This is just part of the function.)
def saveCriteria(request):
title = request.POST.get('quantity')
context = {}
print(title)
return render(request, "home.html", context)
Any help or advice would be greatly appreciated!
You should add if statement before that:
def saveCriteria(request):
context = {}
if request.method == "POST":
title = request.POST.get('quantity')
print(title)
return render(request, "home.html", context)
You should refer to the view function in the html template:
<form action="url of saveCriteria" method="POST">
{% csrf_token %}
<input type="text" name="quantity" placeholder="Repeat" size=2>
<input type="submit" value="Save!">
</form>

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)

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