Я застрял на этом и не уверен, в чем проблема. У меня много отношений между пользователем и адресом. Я пытаюсь создать страницу, которая отображает все адреса пользователя, и пользователи могут быть перенаправлены на другую страницу для редактирования своей адресной информации. У меня есть два маршрута для этого: пользовательский маршрут отображает только адреса и предоставляет address_id для edit_address, который занимается обновлением информации.
Я все время получаю эту ошибку:
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 1 - probably unsupported type.
[SQL: UPDATE addresses SET updated_at=?, address=?, country=?, city=?, post_code=? WHERE addresses.id = ?]
[parameters: ('2020-05-27 19:39:33.594937', ('testing',), ('gb',), ('london',), ('lo346bd',), 1)]
(Background on this error at: http://sqlalche.me/e/rvf5)
Мои модели:
class TimestampMixin(object):
created_at = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)
user_addresses = db.Table('user_addresses',
db.Column("user_id", db.Integer, db.ForeignKey(
"users.id")),
db.Column("address_id", db.Integer, db.ForeignKey("addresses.id")))
class User(db.Model, TimestampMixin, UserMixin):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
(...)
# relationships (many to many)
address = db.relationship("Address", secondary="user_addresses", backref="user", lazy="dynamic")
def __repr__(self):
return f"User('{self.username}')"
class Address(db.Model, TimestampMixin):
__tablename__ = "addresses"
id = db.Column(db.Integer, primary_key=True)
address = db.Column(db.String(200), nullable=False)
country = db.Column(db.String(100), nullable=False)
city = db.Column(db.String(100), nullable=False)
post_code = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f"Address('{self.id}', '{self.address}', '{self.country}', '{self.post_code}')"
Мой шаблон:
<div class="container custom-bg my-4">
<form method="POST" enctype="multipart/form-data" class="py-4">
{{form.csrf_token()}}
<div class="form-group col-12">
{{render_field(form.address , class="form-control",placeholder="Enter your street address")}}
{% for error in form.errors.address %}
<div class="text-danger">{{error}}</div>
{% endfor %}
</div>
<div class="form-group col-12">
{{render_field(form.city , class="form-control",placeholder="Enter your city")}}
{% for error in form.errors.city %}
<div class="text-danger">{{error}}</div>
{% endfor %}
</div>
<div class="form-group col-12">
{{render_field(form.country , class="form-control",placeholder="Enter your country")}}
{% for error in form.errors.country %}
<div class="text-danger">{{error}}</div>
{% endfor %}
</div>
<div class="form-group col-12">
{{render_field(form.post_code , class="form-control",placeholder="Enter your post code")}}
{% for error in form.errors.post_code %}
<div class="text-danger">{{error}}</div>
{% endfor %}
</div>
<div class="form-row justify-content-center">
{{render_field(form.submit, class="btn btn-block btn-secondary")}}
</div>
</form>
</div>
Мое мнение
@ app.route("/profile/settings/edit_address/<address_id>", methods=["POST", "GET"])
@ login_required
def edit_address(address_id):
addresses = Address.query.filter_by(id=address_id).first()
form = UpdateAddressForm(obj=addresses)
form.populate_obj(addresses)
if form.validate_on_submit():
# Update address
addresses.address = form.address.data.lower(),
addresses.city = form.city.data.lower(),
addresses.post_code = form.post_code.data.lower(),
addresses.country = form.country.data.lower(),
db.session.commit()
flash("You have updated your address!", "success")
return redirect(url_for("user_settings"))
return render_template("edit_address.html", title="Update Address", form=form)