【发布时间】:2020-01-09 15:31:13
【问题描述】:
我可以插入,但我不能更新。代码摘录:
app/models.py
class Location(db.Model):
__tablename__ = "my_locations"
loc_id = db.Column(db.Integer, primary_key=True)
loc_name = db.Column(db.String(50), nullable=False)
loc_detail = db.Column(db.String(50), nullable=True)
loc_postal_code = db.Column(db.String(10), nullable=False)
__table_args__ = (db.UniqueConstraint('loc_name', 'loc_detail', name='_location_name_detail_uc'),
)
app/forms.py
class LocationForm(FlaskForm):
loc_id = IntegerField('Loc ID')
loc_name = StringField('Name' , validators=[DataRequired(), Length(min=6, max=50)])
loc_detail = StringField('Detail', validators=[Length(max=50), Optional()])
loc_postal_code = StringField('Postal Code', validators=[DataRequired(), Length(min=4, max=10)])
submit = SubmitField('Submit')
app/routes.py
@app.route('/edit_location/<string:loc_id>', methods=["GET", "POST"])
@login_required
def edit_location(loc_id):
if not current_user.is_authenticated:
return redirect(url_for('index'))
if loc_id == "0":
# Empty form
title_sub = "Add"
form = LocationForm(loc_id=loc_id)
# form.loc_id = loc_id
else:
# Populated form
title_sub = "Edit"
location = Location.query.filter_by(loc_id=loc_id).first()
form = LocationForm(loc_id=location.loc_id, \
loc_name=location.loc_name, \
loc_detail=location.loc_detail, \
loc_postal_code=location.loc_postal_code
)
if request.method == "POST" and form.validate_on_submit():
try:
location = Location(loc_id=form.loc_id.data, \
loc_name=form.loc_name.data, \
loc_detail=form.loc_detail.data, \
loc_postal_code=form.loc_postal_code.data
)
logging.info("edit_location(): location:" + str(location.loc_postal_code))
if location.loc_detail:
loc_str = location.loc_name + ', ' + location.loc_detail
else:
loc_str = location.loc_name
if loc_id == "0":
db.session.add(location)
db.session.commit()
flash('Location (' + loc_str + ') added.', 'success')
else:
db.session.commit()
flash('Location (' + loc_str + ') updated.', 'success')
return redirect(url_for('location'))
except IntegrityError:
logging.error("edit_location(): Intg Exception occurred", exc_info=True)
db.session.rollback()
flash('Location (' + loc_str + ') already exists.', 'error')
except DatabaseError:
logging.error("edit_location(): DB Exception occurred", exc_info=True)
db.session.rollback()
except Exception as e:
flash('Error in form, site administrators have been notified. We apologize for the inconvenience.', 'error')
logging.error("edit_location(): Exception occurred", exc_info=True)
return render_template('edit_location.html', title=title_sub + " Location", loc_id=loc_id, form=form)
app/templates/edit_location.html
{% extends "main_page.html" %}
{% block content %}
<div class="edit-location">
<div class="page-header">
<h2>{% block title %}{{title}}{% endblock %}</h2>
</div>
{% from "_formhelpers.html" import render_field %}
<form method=post name="editLocationForm" action="{{ url_for('edit_location', loc_id=form.loc_id.data) }}">
{{ form.csrf_token }}
<input type="hidden" name="loc_id" value="{{ form.loc_id.data }}">
<table>
<tr>{{ render_field(form.loc_name) }} </tr>
<tr>{{ render_field(form.loc_detail) }}</tr>
<tr>{{ render_field(form.loc_postal_code) }}</tr>
<tr>
<td></td>
<td><small id="locDetail" class="form-text text-muted">e.g.: Rink A, Field #2, West Court</small></td>
</tr>
<tr>
<td></td>
<td>
<a href="#" class="btn btn-primary" onClick="document.editLocationForm.submit();" role="button"> <span>✓</span> Submit</a>
<a class="btn btn-primary" href="{{ url_for('location') }}" role="button"> <span>×</span> Cancel</a>
</td>
</tr>
</table>
<p>
</form>
</div>
{% endblock %}
当我使用edit_locations 插入时,我的loc_id = 0,并且MySQL 提交按预期工作。
当我更新时,我会关注/edit_locations/5 或/edit_locations/293 之类的链接。表单按预期预填充,我更新了 loc_postal_code,但是当我单击 Submit 时,它不会更新后端的记录。
我可以在日志中看到新的loc_postal_code,所以我知道新值存在。
【问题讨论】:
标签: python flask flask-sqlalchemy mysql-python flask-wtforms