3

I want to save age_s, age_e , gender and filename in SQLite database using codes below, but I have a problem.

When I upload the file, my file name is stored in the SQLite database, but the file itself is not stored in my system directory. How can I save a file in my system directory ?

I know that the problem is from the html file but I can not save the file in the directory and save the file name in the database, both actions at the same time.

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()

1 Answer 1

1

Try saving it to your preferred path, per Flask docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.