0

APP CODE : There is no entry in the database and i am new at Flask and i am not able to connect to database and get entry into it and i am confused is my code is at all right

from flask import *
from wtforms import *
from wtforms.validators import Required
from flask.ext.wtf import Form
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = 'MY CSI FORM'

branch_choices = [('CSE','CSE'),('ECE','ECE'),('MEC','MEC'),('CIVIL','CIVIL')]
year_choices = [('1st','1st'),('2nd','2nd'),('3rd','3rd'),('4th','4th')]
cmem_choices = [('Yes','Yes'),('No','No')]

class CSIForm(Form):
    er = IntegerField('Enrollment No',validators=[Required()])
    name = StringField('Name', validators=[Required()])
    branch = SelectField('Branch',choices=branch_choices, validators=[Required()])
    year = SelectField('Year',choices=year_choices, validators=[Required()])
    cmem = SelectField('CSI Member',choices=cmem_choices,validators=[Required()])
    sop = TextAreaField('Statement of Purpose', validators=[Required()])
    submit = SubmitField('Submit')

DATABASE CODE : Code for database creation in SQLAlchemy dont know its correct or not

db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

class CSI(db.Model):
    __tablename__ = 'form'

    er = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    branch = db.Column(db.String(3))
    year = db.Column(db.String(3))
    cmem = db.Column(db.String(3))
    sop = db.Column(db.String(50))

    def __init__(self, er, name, branch, year, cmem, sop):
        self.er = er
        self.name = name
        self.branch = branch
        self.year = year
        self.cmem = cmem
        self.sop = sop

def connect_db():
    db.create_all()

App running and connection

@app.route('/', methods=['GET', 'POST'])
def index():
    form=CSIForm(request.form)
    connect_db()
    if form.validate_on_submit():
        csi = CSI()
        form.populate_obj(csi)
        flash('Thanks for registering')
    return render_template('form.html',form=form)

if __name__ == "__main__":
    app.debug='True'
    app.run()

1 Answer 1

1

You'll probably want to read up on sessions in SQLAlchemy. You need to add csi to your current session and commit the transaction.

def index():
    form = CSIForm(request.form)
    connect_db()
    if form.validate_on_submit():
        csi = CSI()
        form.populate_obj(csi)

        # These lines are new.
        db.session.add(csi)
        db.session.commit()

        flash('Thanks for registering')
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.