How to save file in database and a directory using flask SQLAlchemy?











up vote
1
down vote

favorite












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









share|improve this question




























    up vote
    1
    down vote

    favorite












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









    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











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









      share|improve this question















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






      python flask flask-sqlalchemy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 10:13









      Dinko Pehar

      8192324




      8192324










      asked Nov 20 at 6:31









      dafi mock

      245




      245





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387469%2fhow-to-save-file-in-database-and-a-directory-using-flask-sqlalchemy%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387469%2fhow-to-save-file-in-database-and-a-directory-using-flask-sqlalchemy%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen