I'm trying to get value from dropdown box into variable and then store it. I'm new to Flask and cant find anything in the documents about it.
But I dont know how to get the value from dropdown list with request.form or any other why in that matter.
My flask code in app.py
#app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
title = request.form['title']
link = request.form['link']
shown = request.form['shown']
#I hardcoded the id here too see basic function.
kate = Category.query.filter_by(id = 2).first()
add_into = Entries(title, link, shown, kate)
db.session.add(add_into)
db.session.commit()
And here is the html for it.
<form action="{{ url_for('add_entry') }}" method=post class="add-entry custom">
<dl>
<dt>Title:
<dd><input type=text size=120 name=title>
<dt>Link:
<dd><input type=text size=120 name=link>
<dt>Shown:
<dd><input type=text size=120 name=shown>
<label for="customDropdown">Category</label>
<select style="display:none;" id="customDropdown">
{% for c in cate %}
{% if c.id == 1 %}
<option id="{{ c.name }}" name="{{ c.name }}" SELECTED>{{ c.name }}</option>
{% else %}
<option>{{ c.name }}</option>
{% endif %}
{% endfor %}
</select>
<dd><input class="success button" type=submit value=Post it!>
</dl>
</form>
A select tag, like an input tag, needs a "name" attribute on it if you wish to have the value passed as form data.
<select name="name" style="display:none;" id="customDropdown">
Now, you should be able to access it through request.form['name'] as you have been your input elements.
Related
Sorry for my bad english
I've got "topics.html" file, that extends "base.html".
In "base" I've got search form. In "topics" I've got any checkboxes. How can I connect 2 forms in 1 request?
Base:
<form id="form_1" action="{% url 'topics' %}"><input type="search" id="search" name="search" placeholder="Search"></form>
Topics:
<form id="form_1" action="{% url 'topics' %}">
<div class="typess">
<h1 class="vk">Categories:</h1>
{% for typee, name in types.items %}
<label>
<input type="checkbox" style="display:none" value="{{ typee }}" name="category" {% if typee in categories %} checked {% endif %}>
<span class="typee" title="{{ name }}"><i class="{{ typee }}"></i>{{ name }}</span>
</label>
{% endfor %}
</div>
</form>
It should connect in "topics" function:
def topics(request):
info = []
categoriess = request.GET.getlist('category')
typess = request.GET.getlist('type')
search = request.GET.get('search')
if categoriess:
...
But when I run code, it's not see the checkboxes
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")}}')
I am trying to get the selected value in the dropdown to add to the cart. The way I have it prints out different dropdowns but submits the data into the cart. I just want one dropdown that submits the selected value. Thank you.
{% for product in products %}
<form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug 1 %}'>
<select id="menulist">
<option>{{ product.name }}: ${{ product.price }}</option>
{% endfor %}
</select>
<button type = 'submit' class ="btn btn-info btn-md" class ='pull-right'>Add To Order</button>
</form>
Simply two things need.
First, You should setup option's value. second, forloop should target only option, not whole form.
<form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug 1 %}'>
<select id="menulist" name="{# your select's name here #}">
{% for product in products %}
<option value="{{ product.id|slugify }}">{{ product.name }}: ${{ product.price }}</option>
{% endfor %}
</select>
<button type = 'submit' class ="btn btn-info btn-md" class ='pull-right'>Add To Order</button>
</form>
This code snippet show two different point. 1. option have value, select has name. 2. forloop should in select tags.
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>
I have a Flask-WTF form fields in for loop. I want to post the new quantities for each item.
I am reading about field list. I still dont understand but i think they might be the answer.
#app.route('/checkout')
def checkout():
form = CartForm()
for item in current_user.cart:
product = Product.query.get(item.product_id)
cart_items.append({product: item.quantity})
return render_template('checkout.html',cart_items=cart_items,form=form)
{% for item in cart_items %}
{% for product, quantity in item.items() %}
{{product.name}}
{{product.price}}
{{form.quantity }}
{% endfor %}
{% endfor %}
Problem1: When looping over each Each Flask-WTF form field has the same name.
The output
<select id="quantity" name="quantity"><option value="1">1</option></select>
<select id="quantity" name="quantity"><option value="1">1</option></select>
problem2: how save in the backed if each form has a different name.
I have the same problem exactly! But I solve it without Flask-WTF, the solution below was based on my app. I have an album edit page, I need to loop a text input for each picture in album, then save the text for each picture.
I loop the input in HTML, notice I set the action value for another view function and use each photo's id as each text input's name:
<form action="{{ url_for('edit_photo', id=album.id) }}" method="POST">
<ul>
{% for photo in photos %}
<li>
<img class="img-responsive portrait" src="{{ photo.path }}" alt="Some description"/>
<textarea name="{{ photo.id }}" placeholder="add some description" rows="3">{% if photo.description %}{{ photo.description }}{% endif %}</textarea>
</li>
{% endfor %}
</ul>
<hr>
<input class="btn btn-success" type="submit" name="submit" value="submit">
Then I loop the picture and save the input data (get it's value by it's id):
#app.route('/edit-photo/<int:id>', methods=['GET', 'POST'])
#login_required
def edit_photo(id):
album = Album.query.get_or_404(id)
photos = album.photos.order_by(Photo.order.asc())
if request.method == 'POST':
for photo in photos:
photo.about = request.form[str(photo.id)]
db.session.add(photo)
return redirect(url_for('.album', id=id))
return render_template('edit_photo.html', album=album, photos=photos)