我想使用以下代码在SQLite数据库中保存age_s
,age_e
,gender
和filename
,但是我有一个问题。
当我上传文件时,我的文件名存储在SQLite数据库中,但是文件本身未存储在我的系统目录中。如何在我的系统目录中保存文件?
我知道问题出在html文件,但是我不能同时将文件保存在目录中和将文件名保存在数据库中。
app.py
@app.route("/new_contact", methods=('GET', 'POST'))
def new_contact():
'''
Create new contact
'''
form = ContactForm()
if form.validate_on_submit():
my_contact = Contact()
form.populate_obj(my_contact)
db.session.add(my_contact)
try:
db.session.commit()
# User info
flash('Contact created correctly', 'success')
return redirect(url_for('contacts'))
except:
db.session.rollback()
flash('Error generating contact.', 'danger')
return render_template('web/new_contact.html', form=form)
new_contact.html
{% extends 'layouts/master.html' %}
{% block title %}New contact{% endblock %}
{% block body %}
<h1>New contact</h1>
<form action="{{ url_for('new_contact') }}" method="post">
{{ generate_fields(form) }}
<input type="submit" class="btn btn-success" value="Add">
</form>
{% endblock %}
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField,SelectField,IntegerField,FileField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import DataRequired, Email, Length
class ContactForm(FlaskForm):
age_s = SelectField(u'age_s', choices=age_types)
age_e = SelectField(u'age_e', choices=age_types1)
#age_e = IntegerField('age_e', validators=[Length(min=-1, max=100, message='You cannot have more than 100 characters')])
gender = SelectField('gender', choices=gender_types)
#filename = StringField('filename', validators=[Length(min=-1, max=20, message='You cannot have more than 20 characters')])
filename = FileField()