Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models
To combine Flask-WTF and Flask-SQLAlchemy to edit database models, you can follow these steps:
- Import the necessary modules:
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from flask_sqlalchemy import SQLAlchemy
- Create an instance of the Flask app and configure the SQLAlchemy database:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
db = SQLAlchemy(app)
- Define your database model using SQLAlchemy's
Model
class:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
- Create a form to edit the database model using Flask-WTF:
class EditUserForm(FlaskForm):
username = StringField('Username')
email = StringField('Email')
submit = SubmitField('Save Changes')
- Create a route to handle the form submission and update the database model:
@app.route('/edit/user/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
user = User.query.get_or_404(user_id)
form = EditUserForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
return redirect(url_for('user_profile', user_id=user.id))
return render_template('edit_user.html', form=form)
- Create a template file (e.g.,
edit_user.html
) to display the form:
<form method="POST" action="{{ url_for('edit_user', user_id=user.id) }}">
{{ form.csrf_token }}
{{ form.username.label }} {{ form.username }}
{{ form.email.label }} {{ form.email }}
{{ form.submit }}
</form>
These steps involve importing the necessary modules, configuring the Flask app and SQLAlchemy, defining the database model, creating a form using Flask-WTF, handling the form submission to update the database model, and creating a template to display the form.