Home > Mobile >  SQLite database not updating after submiting form from flask-wtforms
SQLite database not updating after submiting form from flask-wtforms

Time:03-27

These are my different files, not all though. Everything works fine until the part where I submit a form. I suspect it has something to do with the linking of the database if that makes sense? #init.py

import os
from os import path
from venv import create
from flask import Flask, render_template, flash, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from auth import auth
from models import db
from main import app
basedir = os.path.abspath(os.path.dirname(__file__))
DB_NAME = "bookings.sqlite"
app.config\['SECRET_KEY'\] = 'Thisissupposedtobesecret!'
app.config\['SQLALCHEMY_DATABASE_URI'\] = 'sqlite:///'   os.path.join(basedir, DB_NAME)
app.config\['SQLALCHEMY_TRACK_MODIFICATIONS'\] = False
app.register_blueprint(auth, url_prefix="/")
db.init_app(app)

def create_database(app):
if not path.exists('V3/'   DB_NAME ):
db.create_all(app=app)

create_database(app)

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

#forms.py

from flask_wtf import FlaskForm
from wtforms import (StringField, BooleanField, DateTimeField,
RadioField,SelectField,
TextAreaField,SubmitField)
from wtforms.validators import DataRequired

class SignUpForm(FlaskForm):
name = StringField("Your FULL Name", validators=\[DataRequired()\])
(form questions)
submit = SubmitField("Book")

#models.py

from main import app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy(app)
Migrate(app,db)

class Booking(db.Model):
__tablename__ = "bookings"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.Text)
(other colums)

    def __init__(self,name):
        self.name = name

Tried to submit form which was successful but was not updated in the database

CodePudding user response:

You need to push a context so you can access the database https://flask.palletsprojects.com/en/2.0.x/appcontext/

def create_database(app):
  if not path.exists('V3/'   DB_NAME ):
    with app.app_context():
        db.create_all()

CodePudding user response:

Under models.py added

    def __init__(self,name,x,y,z):
    self.name = name
    self.x = x
    self.y = y
    self.z = z

Under auth.py added

if request.method == 'POST':
    name = form.name.data
    x = form.x.data
    y = form.y.data
    z = form.z.data

  
    
    new_booking = Booking(name=name,x=x,y=y,z=z)
    db.session.add(new_booking)
    db.session.commit()
    
    return redirect(url_for('auth.bookings'))
else:
    return render_template('bookings.html', form=form)

this has solved the issue, although i do not exactly understand why but it solved it

  • Related