Creating variable numbers of text boxes using Python Flask? - python

My website has a search bar, and it takes in a search query. Depending on the length of the query (number of characters, for example), I want to create more or less text boxes, for a maximum of 10. (The total number doesn't really matter -- I just don't know how to make a variable number of text boxes in general.) Thus, what would be the best way to do this?
#app.route('/searchQuery', methods=['POST'])
def searchQuery():
searchquery = request.form['searchQuery']
print searchquery
searchquery += " || python added this line!"
return render_template('simplesearch.html', content=searchquery)
<div><center>{{content}}</center></div>
However, if I want to create new divs for up to 10 unique items, what would be the best way to do this?

Okay,
So a basic example of what you are trying to do. Note: this is quick code but should lead you in the right direction:
your_file.py
#app.route('/')
def index():
return render_template('index.html')
#app.route('/searchQuery', methods=['POST'])
def search_query():
sq_ = request.form.get('searchQuery')
print(sq_)
return render_template('simplesearch.html', search_query=sq_)
index.html
<form action="{{ url_for('search_query') }}" method="post">
<input type="text" name="searchQuery" id="searchQuery"><input type="submit" value="Submit">
</form>
simplesearch.html
<table>
{% for x in range(search_query | int) %}
<tr>
<td>
<input type="text" value="{{ x }}">
</td>
</tr>
{% endfor %}
</table>
Basically you are going to capture the "number" that you pass in. I would suggest putting in some checks. Then use Jinja to render the text boxes. Which you can then post to a new page or do whatever with it.

Related

How to render results from API based on the user's search using Django

As you can see in the picture below I'm trying to have the user search for a given country, start/end date and get the result of "Confirmed Cases" and "Date" back from the API, but I'm not sure how to do it.
I tried using this API, to fill the drop-down menu of the countries -->
https://api.covid19api.com/summary
but this is the other API that I have to use but while changing the parameters for the country and dates -->
https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z
Here are snippets of my code:
views.py
def home(request):
# second_response = requests.get('https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json()
second_response = requests.get('https://api.covid19api.com/summary').json()
my_list = []
for i in range(0, len(second_response['Countries'])):
my_list.append(second_response['Countries'][i]['Country'])
if request.method=='POST':
selected_country = request.POST['selected_country']
print('here', selected_country)
return render(request, 'home.html', {'my_list': my_list})
home.html
<div class="container justify-content-center">
<form action="{% url 'home' %}" method="post">
{% csrf_token %}
<label for="selected_country" style="margin-right: 5px;"> Select a Country, Start & End Dates : </label>
<select name="selected_country" >
{% for object in my_list %}
<option value="">{{object}}</option>
{% endfor %}
</select>
<label for="startdate"></label>
<input type="date" id="startdate">
<label for="enddate"></label>
<input type="date" id="enddate">
<input type="submit" value="Search" />
</form>
</div>
PLUS: when I click on "search" i should get the value of the selected_country because I tried printing it, but it doesn't show for some reason, so the method is post but for some reason I can't get back the selected_country
Any help is appreciated
JAVASCRIPT
if you have any solid grasp of javascript i recommend you do that in javascript, because it will just make it better and easier
otherwise :
view.py
def handler(request):
if request.method=='POST':
selected_country = request.POST['selected_country']
startDate= request.POST['startdate']
endDate= request.POST['enddate']
request_handler = requests.get(f"https://api.covid19api.com/country/{selected_country}/status/confirmed?from={startDate}T00:00:00Z&to={endDate}T00:00:00Z")
if request_handler.status_code=200:
#To prevent errors
request_json=request_handler.json()
else:
pass # do something
return render(request, 'result.html', {"json":request_json})
#you should handle the data at the front end using jinja blocks
note : i don't know much about Django so the code may break

Python & Flask HTML - Making n number of textboxes based on variable

I have a flask webpage I am trying to create. When users register for an account, they declare the number of agricultural fields they have. This is saved in a MySQL database. From this, I need users to add information on another input page. This input page should have "n" number of textboxes based on the number of fields they have.
Is there anyway to create "n" number of textboxes in HTML? I can read in the number of fields from their account but cannot find a way to create a variable number of textboxes within HTML.
I do not need this to be dynamic (the user add or remove) this needs to be a FIXED amount of textboxes.
I'm going to assume that because of flask you are using jina2 as your rendering engine, let's call the number of fields that need to be created n, you can just use the loop structure
{% for i in range(n) %}
<input name="field-{{i}}" />
{% endfor %}
you can get more info at https://jinja.palletsprojects.com/en/3.0.x/templates/#for
if you need more complex forms, I would recommend using WTForms.
Found a solution, it is a little ugly but should work.
in your html:
<table>
{% for x in range(fields | int) %}
<tr>
<td>
<input type="text" value="{{ x }}">
</td>
</tr>
{% endfor %}
</table>
in python:
def irrigation_input():
...... non important stuff here.....
fields=account_info_irr[9]
int(float(fields))
return render_template('irrigationinput.html',fields=fields)

Specifying user inputs by dynamic row from HTML form using Flask

In HTML I have a form with 4 user inputs in a row inside a table. However, the number of rows that appear dynamically varies.
<form action="/edit" method="post">
<table>
<tbody>
{% for row in profile_display['rows'] %} <!--# of rows that appear depend on this-->
<tr>
<td> <!--user input 1-->
<form>
<input id={{row[0]~'seq'}} name='seq' class="w-75" type="number" step=1 value="{{row[0]}}" ondblclick="editSeq(`{{row[0]~'seq'}}`);" readonly>
</form>
</td>
<td> <!--user input 2-->
<form>
<input id={{row[0]~'code'}} name='ing_code' class="w-75" value="{{row[1]}}" ondblclick="editCode(`{{row[0]~'code'}}`)" readonly>
</form>
</td>
<td>{{row[2]}}</td>
<td> <!--user input 3-->
<form>
<input id={{row[0]~'weight'}} name='weight' class="w-75" type="number" step=.001 value="{{row[3]}}" ondblclick="editWeight(`{{row[0]~'weight'}}`);" readonly>
</form>
</td>
<td> <!--user input 4-->
<form>
<input id={{row[0]~'ret'}} name='ret_code' class="w-75" value="{{row[4]}}" ondblclick="editRet(`{{row[0]~'ret'}}`)" readonly>
</form>
</td>
</tbody>
</table>
<input type="submit">
</form>
In Python, I am trying to create a function that updates a dataframe, profile_df, which contains preexisting data but can be updated based on user input in the HTML form.
#app.route('/edit', methods=['GET', 'POST'])
def edit():
global profile_df
if request.method == 'POST':
profile_df=profile_df[profile_df['Food code']==food_display['Food Code']]
for index, row in profile_df.iterrows():
row['Seq num']=request.form.get('seq')
row['Ingredient code']=request.form.get('ing_code')
row['Ingredient weight (g)']=request.form.get('weight')
row['Retention code']=request.form.get('ret_code')
return redirect('/')
While I can specify exactly which cells to update in the profile_df by using row['col'], I do not know how to specify exactly which cells to grab the user input from. I know I can grab user input using the 'name' attribute in the form, which I am doing, but since the number of rows in the form varies, just grabbing by 'name' wouldn't work. I am thinking of narrowing the request.form.get even further by somehow specifying the row, but am unsure how to do so. Below is my attempt which doesn't work but hopefully makes my intent clear. Basically, I am trying to further specify the exact row (# rows varies) in which a user input appears by both name and something else.
#app.route('/edit', methods=['GET', 'POST'])
def edit():
global profile_df
if request.method == 'POST':
profile_df=profile_df[profile_df['Food code']==food_display['Food Code']]
for index, row in profile_df.iterrows():
row['Seq num']=row[request.form.get('seq')]
row['Ingredient code']=row[request.form.get('ing_code')]
row['Ingredient weight (g)']=row[request.form.get('weight')]
row['Retention code']=row[request.form.get('ret_code')]
return redirect('/')
I don't think you can do this that way. 'name' tag in form needs to be unique in other case it just overrides.
I would do different 'name' for each row like you did with 'id' and then taking it that way:
for name, value in request.form.items():
print(name, value)

Displaying multiple flask variables from different forms at once in HTML template

I have 2 separate forms on a html template called queries.html, one for inputting a company name and one for inputting keywords as seen below.
<form method="POST">
<p>Enter Company Name:</p>
<p><input type="text" name="company_name"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Name: {{ name }} </p>
<form method="POST">
<p>Enter Keywords:</p>
<p><input type="text" name="keywords"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Keywords: {{ keywords }}</p>
I want to be able to display the form input in the paragraph tags seen below each form.
Below is the relevant flask code:
#app.route('/queries/', methods=['GET', 'POST'])
def queries():
if request.method == 'POST':
if request.form['company_name']:
name = request.form['company_name']
return render_template('queries.html', name=name)
elif request.form['keywords']:
keywords = request.form['keywords']
return render_template('queries.html', keywords=keywords)
return render_template('queries.html')
My problems are, firstly, the company name when entered does display fine where the {{ name }} element is as it should but when inputting a keyword I get a 'bad request' error. Secondly, I did previously have both inputs working but when I would use one form, it would wipe the displayed data from the other, e.g. when inputting a keyword after having already input and displayed a company name, the keyword would appear at the {{ keyword }} element as it should but the company name would disappear. After some research I may need to use AJAX to keep the all elements displayed but not sure if i'm looking in the right direction. It seems this should be a relatively simple issue to solve, please help! Thanks in advance to any responses.
In Place of :
request.form['company_name']
request.form['keywords']
Use this :
request.form.get("company_name")
request.form.get("keywords")
Flask throws error if there is no value in the form input. Using form.get the flask will try to get the value and will handle if there is no value.

Pass var value from HTML to python

Im using python3 and i have this HTMl which create buttons that it gets from a python list :
</style>
</head>
<body>
<ul>
{% for thing in value %}
<form method="get" action="/loader" value="submit">
<button class="button button">{{ thing }}</button>
</form>
{% endfor %}
</ul>
</body>
</html>
my python code:
#app.route("/test", methods=["GET"])
def test():
a = ["a1","a2"]
return render_template('sbutton.html', value=a)
#app.route("/loader", methods=["GET"])
def loader():
data = request.args.get()
print(data)
return render_template('loader.html', value=password)
So i will see buttons a1 and a2 in the website http://localhost/test
And when i press one of them i will redirect to /loader which is a route in my python code to another html.
I want that when i press a button, for example a1, i will get this information back to my python
inside the loader function.
i tried <form method="get" action="/loader" value="submit">
Added the value="submit but i dont get anything under print(data)
I just need to know on which button client clicked when he is redirected to /loader in my code.
I want to keep this value as a var in my python.
Thanks
data = request.args.get() should be called on the exact parameter you want to fetch, e.g. get('username'). Examples are here. As an aside, the data is passed from HTTP, the protocol that the values are transported through, not HTML, the markup language. If you want all values, request.args will return a dictionary with key-value pairs of all GET parameters passed.
I solved it, i was able to catch the button value name like this :
{% for thing in value %}
<form method="get" action="/loader">
<input type=hidden name="{{ thing }}">
<button class="button button">{{ thing }}</button>
</form>
{% endfor %}
And my code it redirects to :
#app.route("/loader", methods=["GET"])
def loader():
data = dict(request.args)
for key in data:
print(key)
return render_template('loader.html', value=password)
So now after i click the button i get the value back to my python /loader function
If client press on a1 button ill get a1 in python.

Categories

Resources