I have a form in HTML that looks like this:
<form action="{{ url_for('home_blueprint.tabledata', tablename = col )}}" method="post">
<select name="tables" placeholder="Table" id="tables" size=3>
{% for col in column_names %}
<option value = "{{ col }}">{{ col }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
</form>
Basically, the form above displays a drop-down list of items {{ col }}. I want that a selected and submitted item from the list above (for example: 'tablename' ) appears in my URL like www.example.com/tabledata/tablename
My flask code is here:
#blueprint.route('/tabledata/<tablename>', methods=['GET', 'POST'])
#login_required
def tabledata(tablename):
return render_template('index.html', tablename=tablename)
In other words, I want to pass a variable from this form to flask using url_for.
How I do that? Thank you in advance!!
There are many ways to do this. I'll go with the most basic one (at least for me).
You just need to tweak your function so if someone submits a GET request, he/she gets the dropdown list, and if the user submits a POST request, fetch the POST data and redirect him/her to another url, the dynamic one.
So your flask code becomes:
#blueprint.route('/tabledata/<tablename>', methods=['GET', 'POST'])
#login_required
def tablename(tablename):
return "Hi"
#blueprint.route('/tabledata')
#login_required
def tabledata():
if request.method == 'GET':
return render_template('index.html', column_names=['abc', 'def', 'ghi']) # Column names were added by me, ignore it
elif request.method == 'POST':
data = request.form.get("tables")
return redirect(url_for('tablename', tablename=data))
And just a little change to the form action:
<form action="{{ url_for('home_blueprint.tabledata')}}" method="POST">
<select name="tables" placeholder="Table" id="tables" size=3>
{% for col in column_names %}
<option class="column" value="{{ col }}">{{ col }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary btn-block btn-large">Submit</button>
</form>
Now if you click on an option, say 'abc', from the dropdown, and submit it, you will be taken to the url www.example.com/tabledata/abc .
Related
Here, 'arr' is a list passed from a previous view. The values(string type) of this list along with the check boxes are successfully being displayed.
<form action="{% url 'prec' %}" method="post">
{% for link in arr %}
<input type="checkbox" name="checks[]" value="{{link}}" />{{link}}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
In views function, I create a list of the fields/boxes checked by the user.
(views.py):
from django.shortcuts import render
def prec(request):
if request.method == 'POST':
var = request.POST.getlist('checks[]')
return render(request, 'Link5_prec.html', {'variables':var})
Then, in another template, I want to display the values checked by the user(along with the index of that checkbox like [0,2,3]). But nothing is being displayed.
(Link5_prec.html):
{% for v in variables %}
<h1>{{v}}</h1>
{% endfor %}
Also, if possible, in the first template, I want to make a checkbox of all the elements in the 'arr' list except the last element.
I need to get data from 2 different forms. The first "index.html" rendering takes a user's selected option and stores it on the variable "item".
on "page2.html", the "item" value is shown here just fine. And again, the user is entering some new data on the textbox input and then it's redirected to the next rendering, "page3.html"
on "page3.html", it is supposed to show both data from the forms on "index.html" and "page2.html" but i'm getting "None" when I try to show the "item" value. Why?
I've tried to do it on separate app.route() routes, but I got the None type value as well.
the app.py file:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.form.get('send') == 'send':
item = str(request.form.get('test1'))
return render_template('page2.html', item=item)
if request.form.get('send2') == 'send2':
item = str(request.form.get('test1'))
text = request.form.get('textbox')
return render_template('page3.html', item=item, text=text)
else:
return render_template('index.html')
app.run(debug=True)
the index.html file:
<div align="center">
<form method="POST" action="{{ url_for('index') }}">
<select name="test1">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
</select>
<button type="submit" name="send" value="send">Send</button>
</form>
</div>
the page2.html file:
<div align="center">
<form method="POST" action="{{ url_for('index') }}">
<h2>Previous selection: {{ item }}</h2><br>
<input type="text" name="textbox" value="Enter text">
<button type="submit" name="send2" value="send2">Send</button>
</form>
</div>
and the page3.html file:
<div align="center">
<h2>Your result is:</h2><br>
<h2>"{{ text }}" and "{{ item }}" </h2>
</div>
store the value of item in a session so that you can access it later. Once you are done you can clear the session like session.pop("session_name", None)
if request.form.get('send') == 'send':
item = str(request.form.get('test1'))
session["test1"]=item
return render_template('page2.html', item=item)
if request.form.get('send2') == 'send2':
item = session.get("test1")
text = request.form.get('textbox')
return render_template('page3.html', item=item, text=text)
I'm trying to get a select option that is selected to stay after the page refresh using Flask. I have attempted to do so with Jinga2, but it's is not working:
<div class="col-sm-4 col-lg-4 col-md-4">
<select class="form-control" id="myselect" name="thing" required>
<option value="" {% if thing=='' %} selected {% endif %} ></option>
<option value="Foo" name="Foo" id="Foo" {% if thing =="Foo" %} selected {% endif %}>Foo</option>
<option value="Bar" name="Bar" id="Bar" {% if thing =="Bar" %} selected {% endif %}>Bar</option>
</select>
</div>
Where the variable energy is populated and passed through with Python. After looking into this, I feel that this is the way to make this work in Flask, though apparently not. Any assistance would be appreciated!
#app,route('/things', methods=['POST']
def things()
if len(facts['thing']) > 11:
energy = [facts['thing'][0:8],facts['thing'][9:]]
else:
energy = [facts['things']]
...
return render_template('thing.html', thing=energy)
Please see this example as it works for what you're trying to do. I can't exactly debug what's going wrong in your code because you've provided me with parts and I don't know what they're doing.
Folder structure
Test
|___templates
| |___things.html
|___Test.py
things.html
<form method="post">
<div class="col-sm-4 col-lg-4 col-md-4">
<select title="thing" class="form-control" id="myselect" name="thing" required>
<option value="" {% if thing=='' %} selected {% endif %} ></option>
<option value="Foo" name="Foo" id="Foo" {% if thing =="Foo" %} selected {% endif %} >Foo</option>
<option value="Bar" name="Bar" id="Bar" {% if thing =='Bar' %} selected {% endif %}>Bar</option>
</select>
<button type="submit">SEND</button>
</div>
</form>
Test.py
from flask import Flask, render_template, request
app = Flask(__name__)
PORT = 5000
#app.route('/things', methods=['GET', 'POST'])
def things():
"""
Accepts both GET and POST requests. If it's a GET request,
you wouldn't have a last selected thing, so it's set to an
empty string. If it's a POST request, we fetch the selected
thing and return the same template with the pre-selected
thing.
You can improve on this and save the last selected thing
into the session data and attempt to retrieve it from there.
"""
thing = ''
if request.method == 'GET':
return render_template('things.html', thing=thing)
else:
thing = request.form.get('thing', '')
return render_template('things.html', thing=thing)
if __name__ == '__main__':
app.run(port=PORT)
The important part is rendering the page with selected in your desired option:
<option value="Foo" selected>Foo</option>
double_j's answer to use templates to insert it into your html works great, but if you're building the dropdown from a list it may be easier to build your html from python:
import flask
import socket
app = flask.Flask(__name__)
all_things = ['Foo', 'Bar', 'Fizz', 'Buzz']
current_thing = None
def show_selection(target):
if target == current_thing:
return 'selected'
else:
return ''
def menu():
template = '''<form action = "things" method = "post">
<select id="target" name="target">
{targets}
</select>
<input type="submit" name="build" value="Build">
</form>
'''
# vvv This is the important part vvv
targets = [f'<option value="{t}" {show_selection(t)}>{t}</option>' for t in all_things]
return template.format(
targets='\n'.join(targets)
)
# ^^^ This is the important part ^^^
#app.route('/things', methods=['GET', 'POST'])
def things():
global current_thing
current_thing = flask.request.form.get('target')
page = menu()
if flask.request.method == 'POST' and 'build' in flask.request.form:
page += f'Building {current_thing}'
else:
page += 'Press Build button'
return page
if __name__ == '__main__':
PORT = 8080
print("Visit http://{}:{} to trigger builds".format(socket.gethostname(), PORT))
app.run(host='0.0.0.0', port=PORT, debug=True)
try this, if you have not already
{% if thing == "Foo" %}
<option value = "Foo" name ="Foo" id="Foo" selected>Foo</option>
<option value = "Bar" name ="Bar" id="Bar">Bar</option>
{% elif thing == "Bar" %}
<option value = "Foo" name ="Foo" id="Foo">Foo</option>
<option value = "Bar" name ="Bar" id="Bar" selected>Bar</option>
{% endif %}
I'm trying to show a confirmation/success message to the user in my Flask app, but I can't figure out how to display it in a modal.
#app.route("/", methods=["POST"]
def sendForm():
form = ContactForm(request.form)
if request.method == 'POST':
if form.validate():
# do stuff with form data
return render_template("contact.html", form=form)
else:
# display error message
else:
return render_template("index.html")
The part where I return the contact.html template is where I need help, I think. Because that page is basically refreshed and shown again after the POST request successfully completes. Need to display a confirm message to the user in a modal instead.
On the front-end, my form is looks like this:
<form method="POST" action="{{ url_for('sendForm') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
{{ render_field(form.email) }}
{{ render_field(form.name) }}
<input id="submit-form" type="submit" value="Send">
</form>
I would do some form of this...
Pass a boolean in your render_template:
submission_successful = True #or False. you can determine this.
render_template("contact.html", form=form, submission_successful=submission_successful))
Then in your template place an if statement
{% if submission_successful %}
// modal elements here
{% endif %}
I'm not sure if i'm going about this completely the wrong way, but in my html template i have a for loop that i want to present multiple forms, and one submit button to submit the data from all forms:
{% for i in Attribute_list %}
<form action="/Project/create/" method=post>{% csrf_token %}
{{ i }}:
<input type=text name={{ i }}><br>
<hr>
{% endfor %}
<input type=submit>
The problem with this is it only submits the last form.
The other problem i'm running into is getting the data back from the view. Since i'm naming the form the variable "i", i don't know how to "get" this data in my views.py:
def create_config(request):
if request.method == 'POST':
data_list = []
for data in request.POST.getlist():
data_list.append(data)
can You check this?
<form action="/Project/create/" method="post">
{% csrf_token %}
{% for i in Attribute_list %}
{{ i }}: <input type="text" name="{{ i }}"><br>
<hr>
{% endfor %}
<input type="submit">
</form>
As I understand without JS regardless how many forms You create only one POST request will be made.
In oyur example HTML is not valid so It can behave different ways in different browsers. But as soon as You have not closed form last one should be submitted.
As for second part
def create_config(request):
if request.method == 'POST':
data_list = []
for data in request.POST.getlist():
data_list.append(data)
I think You should use your Attribute_list. Or You can just iterate over all `POST' variables obtained.
def create_config(request):
if request.method == 'POST':
data_list = []
for key in request.POST:
data_list.append(request.POST[key]) # or .extend(request.POST.getlist(key)