Updating A Record With Wtforms, Sqlalchemy & Flask
Solution 1:
This is an old question, but this was my approach, using Flask-SQLAlchemy. The routes are separate, but they both call on the same template to avoid repeating.
Form can take the object as an argument, and populate the form fields for "updating". The populate_obj method then is called on the form to do just that, changing the object to reflect the new form fields. The new instance can now be added to the db.
@app.route("/add_item", methods=['GET', 'POST'])defadd_item():
form = AddItem()
if form.validate_on_submit():
"""Get instance of version from form data."""
item = Item(field1=form.field1.data,
field2=form.field2.data,
field3=form.field3.data,
)
db.session.add(item)
db.session.commit()
return render_template('add_item.html', form=form)
@app.route("/edit_item/<item_id>", methods=['GET', 'POST'])defedit_item(item_id):
item = db.session.query(Item).get(item_id)
form = AddItem(obj=item)
if form.validate_on_submit():
form.populate_obj(item)
db.session.add(item)
db.session.commit()
return redirect(url_for('home'))
return render_template('add_item.html', form=form)
Solution 2:
First off, POSTing to /add will always insert a new entry, judging by your code. The updating and inserting should be happening in separate endpoints.
SQLAlchemy provides an object-relational mapping between your backend and your database. This means that, not only does SQLAlchemy see those newly constructed forms you're making as different from the one(s) that you've already inserted into the database (despite all their fields being identiacal), but any changes you make to the fields of a mapped object are reflected in that object's database entry.
You can update an object simply by querying it from its table, setting the object's fields to their updated values, and calling db.session.commit()
. So for example:
# Assuming you're using flask-sqlalchemy
form = Entry.query.get(id)
form.title = 'Fred Flinstone'
form.text = 'yabba dabba doo'
db.session.commit(form)
Solution 3:
a concrete example:
classArticle(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True, nullable=False)
# price# stock
category = db.Column(db.String(64))
sub_category = db.Column(db.String(64))
description = db.Column(db.Text())
classArticleForm(FlaskForm):
name = StringField('Name', render_kw={"placeholder": "Nombre del producto"}, validators=[
DataRequired(), Length(max=64)])
category = StringField('Category', validators=[
DataRequired(), Length(max=64)])
sub_category = StringField(
'sub-category', validators=[DataRequired(), Length(max=64)])
description = TextAreaField('Description', render_kw={"rows": 10, "cols": 30}, validators=[
DataRequired()])
@app.route('/update_article/<id>', methods=['GET', 'POST'])defupdate_article(id):
article = Article.query.get(id)
form = ArticleForm(obj=article)
if form.validate_on_submit():
form.populate_obj(article)
db.session.commit()
return redirect(url_for('index'))
return render_template("add_article.html", form=form)
and add_article.html:
{% extends "base.html" %}
{% block title %}
Edit Article
{% endblock %}
{% block styles %}
{{super()}}
<linkrel="stylesheet"href="{{url_for('static', filename='css/login.css')}}">
{% endblock %}
{% block content %}
<divclass="global-container"><divclass="card login-form"><divclass="card-body"><h3class="card-title text-center"><b>Edit Article</b></h3><divclass="card-text">
{% with messages = get_flashed_messages() %}
{% if messages %}
<divclass="alert alert-danger">
{{ messages[0] }}
</div>
{% endif %}
{% endwith %}
<formaction=""method="post"novalidate>
{{ form.hidden_tag() }}
<divclass="form-group">
{{ form.name.label }}<br>
{{ form.name }}<br>
{% for error in form.name.errors %}
<spanstyle="color: red;">{{ error }}</span>
{% endfor %}
</div><divclass="form-group">
{{ form.category.label }}<br>
{{ form.category }}<br>
{% for error in form.category.errors %}
<spanstyle="color: red;">{{ error }}</span>
{% endfor %}
</div><divclass="form-group">
{{ form.sub_category.label }}<br>
{{ form.sub_category }}<br>
{% for error in form.sub_category.errors %}
<spanstyle="color: red;">{{ error }}</span>
{% endfor %}
</div><divclass="form-group">
{{ form.description.label }}<br>
{{ form.description }}<br>
{% for error in form.description.errors %}
<spanstyle="color: red;">{{ error }}</span>
{% endfor %}
</div><divclass="form-group">
{{ form.submit() }}
</div></form></div></div></div></div>
{% endblock %}
Post a Comment for "Updating A Record With Wtforms, Sqlalchemy & Flask"