I am trying to store 2 values in one column and I do not know if it's even possible.
It looks like that. I get data from HTML form like below. It works.
<form action="{{url_for('newBook')}}" method = 'POST'>
<p>Choose Language</p>
<select name=language method="GET" action="/" size="2" multiple>
{% for language in languages %}
<option value= "{{language}}" SELECTED>{{ language }}</option>"
{% endfor %}
</select>
<p><input type='submit' value='Create'></p>
<a href = "{{url_for('showBooks') }}">Cancel</a>
</form>
But it only stored one value in database.
class Book(Base):
__tablename__ = 'Book'
language = Column(String(30)) # how change that?
This is how I get this one value.
languages = ['Polish', 'English']
@app.route('/books/new/', methods=['GET', 'POST'])
def newBook():
if request.method == 'POST':
newBook = Book(language = request.form['language']) # how change that?
session.add(newBook)
session.commit()
flash("New Book Added!")
return redirect(url_for('showBooks'))
else:
return render_template('newBook.html', languages=languages)
That code works but I get only English or Polish value. But I want that I can store sometimes both values. I know that is possible to use request.form.getlist but I didn't find a working example and how to store it in a database.
To retrieve multiple values from a select element, you can change your code to this:
languages = ['Polish', 'English']
@app.route('/books/new/', methods=['GET', 'POST'])
def newBook():
if request.method == 'POST':
newBooks = request.form.getlist('language') # this returns a list of values
session.add(newBook)
session.commit()
flash("New Book Added!")
return redirect(url_for('showBooks'))
else:
return render_template('newBook.html', languages=languages)
As for storing them in a database, you can create another table that stores the languages and link back to your Book
table using a foreign key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.