To retain the form values in the jinja template - python

I have a form that I am using for post the data
<form enctype="multipart/form-data" method="post" action="">
<div class="form-group">
<label>Application Name <span class="mandatory">*</span></label>
<input type="text" class="form-control" name="app_name" id="appname" required maxlength="40">
<button>submit</button>
</div>
</form>
In flask i am fetching the form data and trying to do post method
if request.method == "POST":
application_data = request.form.to_dict()
postedata = post(application_data )
if posteddata:
print("sucessfully posted")
else:
print("unsucessful")
return render_template("application/addapplication.html", data=application_data)
but what I want is when else part executes that means post data doesnot happens i want to retain the values in the form. but, since here page will reload the form data is disapperaring. please can anyone help me in this?

<input type="text" value="{{ request.form.get('app_name','')}}" class="form-control" name="app_name" id="appname" required maxlength="40">
For Select tag, Let's take the data from the Flask flask_option = 'batman'.
<select>
<option {% if flask_option == "superman"%} selected {% endif %} value="superman">Clark</option>
<option {% if flask_option == "batman"%} selected {% endif %} value="batman">Bruce</option>
<option {% if flask_option == "wonderwomen"%} selected {% endif %} value="wonderwomen">Diana</option>
<option {% if flask_option == "aquaman"%} selected {% endif %} value="aquaman">Arthur</option>
</select>
If you are using API for the select options,
let's take the API response like this,
{'response': [
{'value': 'superman', 'inner_text': 'Clark'},
{'value': 'batman', 'inner_text': 'Bruce'},
{'value': 'aquaman', 'inner_text': 'Arthur'},
{'value': 'wonderwomen', 'inner_text': 'Diana'}
]}
You can iterate over the API to generate the select tag,
<select>
{% for value, text in varible_name.response %}
<option {% if flask_option == value %} selected {% endif %} value = '{{value}}'> {{text}} </option>
{% endfor %}
</select>
For textarea, you can use
<textarea>{{reqest.form.get("txt")}}</textarea>
or javascript
$('textarea').text('{{reqest.form.get("txt")}}')

Related

Handling GET and POST in same Flask view, can I pass value from form then pass it on? [duplicate]

This question already has answers here:
How to pass a variable between Flask pages?
(2 answers)
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
I have a form like this
<form method="GET" action="{{ url_for('model3') }}">
<div> Choose a Model:
<select class="form-select" aria-label="Default select example" name="stage">
<option value="Post Flowering" {% if thing=='Post Flowering' %} selected {% endif %}>Post Flowering</option>
<option value="Filling" {% if thing=='Filling' %} selected {% endif %}>Filling</option>
<option value="Filling Ripening" {% if thing=='Filling Ripening' %} selected {% endif %} >Filling-Ripening</option>
<option value="Ripening" {% if thing=='Ripening' %} selected {% endif %}>Ripening</option>
</select>
<input type="submit" value="Submit">
</div>
then I have route like this
#app.route('/WheatDetect', methods=['POST', 'GET'])
def model3():
stage = request.args.get('stage')
print("stage in get-->",stage)
if request.method == 'POST':
print("stage in post-->", stage)
the problem is the first print can get what I have from select option
while the 2nd print always show none...
but I need that value to process my data, but how???
Use
<form method="POST" action="{{ url_for('model3') }}">
Instead of
<form method="GET" action="{{ url_for('model3') }}">
Due to different request method you are not get the value

select entries from database mysql in dropdown, python flask

I want to select data from database table in MySQL. It is procedure in Python
#app.route('/formworkers.html')
def formworkers():
cursor = mysql.connection.cursor()
cur = cursor.execute("SELECT ID_worker, surname FROM workers")
return render_template('formworkers.html', workers0=cursor.fetchall())
And template in Jinja2
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="" method=post class=add-worker >
<dl>
<dt>Surname:
<dd><select name="worker0">
{% for ID_pats, surname in workers0 %}
<option value="{{ ID_worker }}">{{ surname }}</option>
{% endfor %}
</select>
<br><br>
<dd><input type=submit value="Submit">
</dl>
</form>
{% endif %}
{% endblock %}
But the dropdown list does not contain data (for example [Ivanov, Petrov, Sidorov]) from the database, it contain values [surname, surname, surname]. Thank you.
The query outputs a result as a list of dictionaries, so when you unpack it in the for loop, you get only a list of keys "ID_worker" and "surname" .
You can change the template like below to access the values :
{% for worker in workers0 %}
<option value="{{ worker.ID_worker }}">{{ worker.surname }}</option>
{% endfor %}

Django ifequal and if Statement Always Going to Else tags

I am currently trying to compare the product id to the id given in the URL. But the if statement in the template always returns "else" even though testing provides both to be equal.
views.py (where data is given)
def editstatus(request, product_id):
try:
request.session['user_id']
except KeyError:
return redirect("/login")
products = Product.objects.all()
context = {
"product":products,
"theid" : product_id,
}
return render(request, 'posystem/status.html', context)
status.html (with not working if statement)
{%for product in product%}
<tbody>
<tr>
<td>{{product.id}}</td>
<td>{{theid}}</td>
<td>{{product.product_description}}</td>
<td>{{product.product_number}}</td>
<td>{{product.product_quantity}}</td>
<td>{{product.unit_cost}}</td>
<td>{{product.final_cost}}</td>
<td>{{product.status}}</td>
{% ifequal product.id theid %}
<h1>hello</h1>
{% else %}
<h1>hello2</h1>
{% endifequal %}
{% if theid %}
{% if product.id == theid %}
<td><select>
<option value="5 Votes Needed">5 Votes Needed</option>
<option value="Ready to Order">Ready to Order</option>
<option value="Needs to Be Signed">Needs to Be Signed</option>
<option value="Ordered">Ordered</option>
<option value="Recieved">Recieved</option>
</select></td>
<td><form class="" action="/changestatus/{{product.id}}" method="post">
{% csrf_token %}
<button type="submit" name="edit">Save</button>
</form></td>
{% endif %}
{% else %}
<td><form class="" action="/status/{{product.id}}" method="post">
{% csrf_token %}
<button type="submit" name="edit">Edit</button>
</form></td>
{% endif %}
</tr>
</tbody>
{% endfor %}
I am confused on why it will neither work with a ifequal tag nor a normal if tag.
Since product_id is from the URL then it will be a string, not an integer. You need to convert it to an integer.
context = {
"product":products,
"theid" : int(product_id),
}
In Python, and the Django template language, '1' is not equal to 1.

How can I include form value in url_for function from jinja template? [duplicate]

This question already has answers here:
How to get form data from input as variable in Flask?
(2 answers)
Closed 5 years ago.
I want to pass the selected {{ exam[0] }} to the show_exam_form function.
However I could not do that.
Environment
Python 3.6.1
Flask==0.12.2
Jinja2==2.9.6
app.py
#app.route('/exam/<int:exam_id>', methods=['POST'])
def show_exam_form(exam_id):
print(exam_id)
html
<form action="{{ url_for('show_exam_form', exam_id=exam_id) }}" method='POST'>
<select name=exam_id>
{% for exam in exams %}
<option value="{{exam[0]}}">{{exam[1]}}</option>
{% endfor %}
</select>
How can I solve it?
Please let me know if you need more information to solve it.
Thank you!!!
Requesting the id as parameter is not necessary. Here is an example how to handle this selected value for future OPs.
In app.py:
#app.route('/exam', methods=['GET','POST'])
def show_exam_form():
exams = {
"IT-101":"IT Fundamentals",
"IT-201": "Object Oriented Programming",
"IT-301": "Database Management",
"IT-401": "Operating Systems"
}
if request.method == "GET":
return render_template('so.html', exams = exams)
else:
exam_id = request.form["exam_id"]
flash(exam_id)
return render_template('so.html', exams = exams)
In so.html template (in my case it extends a base templete):
{% extends "layout.html" %}
{% block content %}
<form action="{{ url_for('show_exam_form') }}" class="form" method='POST'>
<div class="form-group">
<select name="exam_id" class="form-control">
{% for key,value in exams.items() %}
<option value="{{ key }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
{% endblock %}
Output:
Figure 1: Input Form
Figure 2: Flashing the selected value
I do not need to send the exam_id from jinja to Flask.
Just send via POST and get it with request.form['exam_id'] in the show_exam_form function.

Prevent Form from Clearing with Flask Inheritance

I have a form, which I would like to not get cleared out on submit (post).
I am using <option selected="selected">{{ yourvalue }}</option> to keep the value in the field before generating the other option values. The problem with this is then yourvalue is duplicated in the select box. I could remove yourvalue from the list, numbers, that goes into populating the options, but then things get out of order as the selected value appears at the top. Overall, this just seems like a clunky way to keep the selected value in the form on submit. What is the correct way to do this?
__init__py
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def test():
numbers = [1, 2, 3]
if request.method == "POST":
return render_template('body.html', yourvalue=request.form['number'], numbers=numbers)
return render_template('form.html', numbers=numbers)
app.run()
form.html
<html>
<body>
<form class="form-inline" method="POST" >
<select class="form-control" id="number" name="number" required>
<option value="" disabled selected></option>
<option selected="selected">{{ yourvalue }}</option>
{% for z in numbers %}
<option value="{{ z }}">{{ z }}</option>
{% endfor %}
</select>
<input type="submit" value="Submit">
</form>
{% block body %}{% endblock %}
</body>
</html>
body.html
{% extends "form.html" %}
{% block body %}
You chose {{ yourvalue }}
{% endblock %}
Sorry I misinterpreted your question initially. Could you change the HTML to something like this? Basically adding an Jinja If statement to see if the 'yourvalue' matches 'z' and if so, add "selected" to the option.
<form class="form-inline" method="POST" >
<select class="form-control" id="number" name="number" required>
<option value="" disabled selected></option>
{% for z in numbers %}
<option {% if yourvalue = z %}
selected
{% endif %}
value="{{ z }}">{{ z }}</option>
{% endfor %}
</select>
<input type="submit" value="Submit">
</form>

Categories