Get value of a form input by ID python/flask - python

How do you get the actual value of the input id after you send it in Flask?
form:
<form action="" method="post">
<input id = "number_one" type="text" name="comment">
<input type="submit" value = "comment">
</form>
like, what I am trying to say is when the form is sent (i.e. when you do this):
request.form.get("comment")
the value of the text field is passed. What I can't figure out is how to get the value of the id.
So, when the form is sent we could then tell from which form the info was coming from, because each form has a unique id. In this case the id is number_one.
So, how do we go about getting the actual literal value of the id and not the text input?

You can't. The id value is not part of the form data set sent by the browser.
If you need to identify the field, you'll have to either add the id to the input element name, or if the id is generated by Javascript code, perhaps store the information in an extra hidden field.
Adding the id to the name could be done with a delimiter perhaps:
<input id = "number_one" type="text" name="comment.number_one">
which would require you to loop over all form keys:
for key is request.form:
if key.startswith('comment.'):
id_ = key.partition('.')[-1]
value = request.form[key]

There is a one way to identify the fields and also multiple forms together....
use this
<input value = "1" type="hidden" name="my_id">
so at your view file you can retrieve this value.
my_id = request.form.get("my_id","")
print my_id
your output will be
1
you can also do this...
my_id = request.form.get("my_id","")
if my_id == "1":
** for example **
value = request.form.get("any_parameter_of_form","")

Related

How to get USER input from html and search for it in databse with Python

I have a database and i want to search in it with this HTML
<form action="/question/search" method="POST">
<input id="search" type="text" placeholder="Search.." name="search">
<button id="search" type="submit">🔍</button>
</form>
I get the data in my function
#app.route("/question/search",methods=["POST"])
def search():
search_result = request.form.get("search")
story = data_handler.get_search_result(search_result)
return render_template('search_resoult.html', stories=story)
but i just cant figure out the SQl for it i tried :
#database_common.connection_handler
def get_search_result(cursor,item):
my_sql = "SELECT * FROM question WHERE title LIKE %s OR message LIKE %s"
my_resoult = (item)
cursor.execute(my_sql, my_resoult)
resoult = cursor.fetchall()
return resoult
I just want to all the data that has my_result in the title or in the message.
It always gives me this error:
TypeError: not all arguments converted during string formatting
The problem is that your query requires 2 values to be unpacked, but you're only giving a single one (item). If you want to use item as the condition for both title LIKE and message LIKE, you should expand my_resoult:
my_resoult = (item, item)

How to get multiple elements from a form using request.form.get

I have a form inside an html file, this form is creating new input fields in which the user is supposed to type some info. Later, i wanna pass all those values into my python main file (application.py)and do somethings with them. The problem is that i don't know how to pass several values into python. Normally i would use this
request.form.get("username")
which returns me the value of the input field named "username" inside my html file. Now, i have several input fields which are generated when the user pushes a button:
$("#add_dream").click(function(){
$("#"+x).append('<button type="submit" style="height:30px;" class="delete"
id="ix">Remove</button>')
document.getElementById("ix").setAttribute("id","delbuttdream"+j)
}
This is not the whole code, but it may help to understand what i'm saying. This new fields can be created an deleted as many times as the user wants to, so the name of the fields or their ids don't follow a straight order (1,2,3,4...). I wanna know if there's anyway in which i can call from python using request.form.get all the elements of the same clase or with certain id and not only one of them by name
Example form:
Items in random order</br>
<form method="POST">
<input name="item4" value="val4"/></br>
<input name="item2" value="val2"/></br>
<input name="item1" value="val1"/></br>
<input name="item3" value="val3"/></br>
<button type="submit">OK</button>
</form>
request.form behaves like dictionary and you can use request.form.items() to get all keys and values and filter them.
for key, val in request.form.items():
#print(key,val)
if key.startswith("item"):
print(key, val)
or request.form.keys() to get only keys to filter and sort them.
keys = request.form.keys()
keys = [key for key in keys if key.startswith("item")]
keys = sorted(keys)
for key in keys:
#print(key, request.form[key])
print(key, request.form.get(key))
Minimal working code:
from flask import Flask, request, render_template_string
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print('--- original order ---')
for key, val in request.form.items():
if key.startswith("item"):
print(key, val)
print('--- sorted ---')
keys = request.form.keys()
keys = [key for key in keys if key.startswith("item")]
keys = sorted(keys)
for key in keys:
#print(key, request.form[key])
print(key, request.form.get(key))
return render_template_string('''Items in random order</br>
<form method="POST">
<input name="item4" value="val4"/></br>
<input name="item2" value="val2"/></br>
<input name="item1" value="val1"/></br>
<input name="item3" value="val3"/></br>
<button type="submit">OK</button>
</form>
''')
if __name__ == '__main__':
app.run(debug=True)
If there are multiple keys, and the keys are the same, it will return only the first item.
If you need a list with these values, use simply .getlist().
Example:
request.form.getlist('keyname'))

How do I get ID of a submit type button on its click in Python + HTML + web2py?

I am using WEB2PY framework
For example, I have a lot of submit type buttons on my webpage and when I click one I want to pass that specific clicked button ID from HTML to a Python variable.
Another problem is that when I use a Python variable inside of a SQlite insert statement then I am getting an error.
My HTML code:
<form method = "POST">
Case:
<input type="text" name="case_qty" value = 0><br>
Pcs:
<input type="text" name="pcs_qty" value= 0><br>
<button type="submit">Add to cart</button>
</form>
PYTHON CODE:
def fortune():
case = 0
pcs = 0
proddict = {}
productrows = db(db.products).select()
//my db contains product id & name
for x in productrows :
proddict[x.id]= x.product_name
if request.post_vars:
case = int(request.post_vars.case_qty)
pcs = int(request.post_vars.pcs_qty)
product= proddict[]//i want submitted button id number inside []
sql = "insert into cart(product_name,case_qty,pcs_qty)values(product,case,pcs)"
// another problem is when i use variable
//inside values i am getting error
r = db.executesql(sql)
return locals()

Creating a simple django form

I am new to django and and I'm trying to use forms.I want to create a form with two CharFields. Here is where I am so far -
forms.py
from django import forms
class NameForm(forms.Form):
key = forms.CharField(label='Enter Key:', max_length=2)
value = forms.CharField(label='Enter Value:', max_length=4)
template.html
<form action="/new-page/" method="GET">
{{ form }}
<input type="submit" value="Submit" />
</form>
What I want is to take the data in this form and simply use that data in my function myfunc
views.py
def myfunc(request,id):
key = request.GET.get('key')
value = request.GET.get('value')
where id is the id of the page where the form appears like so url/places/1/
I want the action to send the id and the key,value pair to the function to use on submit.Validation is not required. Can someone help me understand the concept here.
Your views.py should look like:
def myfunc(request, id):
form = NameForm(request.GET or None)
if form.is_valid():
key = form.cleaned_data['key']
value = form.cleaned_data['value']
# do something with key and value

Why does the "engine" capitalize this variable. Can it be hidden?

The view:
def GRID_ServerDropDownSearch(request):
if 'r' in request.GET and request.GET['r']:
r = request.GET['r']
servers = SERVERS.objects.get(name=r)
drives = servers.drives_set.all()[0:]
memory = servers.memory_set.all()[0:]
return render_to_response('GRID_ServerDropDownSearchResults.html',
{'servers':servers, 'query':r, 'drives':drives, 'memory':memory})
else:
return render_to_response('GRID_search_form.html', {'error': True})
The form:
class ServerDropDownForm(forms.Form):
r = forms.ModelChoiceField(queryset = SERVERS.objects.all(), required=False)
The template:
<div>
<form action="/ServerDropDownSearch/" method="GET">
{{ form.as_table }}
<input type = "Submit" value = "Submit">
</form>
</div>
The resulting drop-down form works flawlessly. However, immediately to the left of the drop-down list is an "R" (capital r). I know it has to do with the "r" specified in the above code. (If I replace each incidence of r with, say, z then a "Z" appears). However:
WHY does it get capitalized ? Is this just the default case specified in the engine ?
How can I hide that "R" so that, instead, it can indicate "Select A Server", or something more descriptive.
Thanks in advance.
Django derives the label for a form field from the corresponding variable name, but "humanizes" it. For example, a field called my_variable would translate to "My variable".
The simplest way to fix this would be to give a more human-readable name to the field:
server = forms.ModelChoiceField(queryset = SERVERS.objects.all(), required=False)
However, you can also pass a string to use as the label via the form field's label parameter:
r = forms.ModelChoiceField(queryset = SERVERS.objects.all(), required=False, label='Select a server')

Categories

Resources