我对动态设置默认选择字段有一些问题,我认为这很有用。模型是这样的:
class State(db.Model):
__tablename__ = 'states'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
class City(db.Model):
__tablename__ = 'cities'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
state_id = db.Column(db.Integer, db.ForeignKey('states.id'))
state = db.relationship(State, backref='state')
class User(UserMixin, db.Model):
...
city_id = db.Column(db.Integer, db.ForeignKey('cities.id'))
city = db.relationship('City', backref='city')
表格是这样的:
class UserEditForm(FlaskForm):
...
state = SelectField("state", coerce=int)
city = SelectField("city", coerce=int)
....
def __init__(self, state_id, *args, **kwargs):
super(UserEditForm, self).__init__(*args, **kwargs)
self.state.choices = [(state.id, state.name)
for state in State.query.order_by('name').all()]
self.city.choices = [(city.id, city.name)
for city in City.query.filter_by(state_id=state_id).order_by('name').all()]
视图是这样的:
@dashboard.route('/useredit', methods=['GET', 'POST'])
@login_required
def useredit():
....
user = current_user._get_current_object()
form = OrganEditForm(state_id=user.city.state_id, state=user.city.state_id, city=user.city_id)
....
它运行良好并正确设置 Selectfield 默认值。但我改变了这样的代码:
鉴于:
@dashboard.route('/useredit', methods=['GET', 'POST'])
@login_required
def useredit():
....
user = current_user._get_current_object()
form = OrganEditForm(obj=user)
....
在表格中
def __init__(self, *args, **kwargs):
super(UserEditForm, self).__init__(*args, **kwargs)
self.state.choices = [(state.id, state.name)
for state in State.query.order_by('name').all()]
self.city.choices = [(city.id, city.name)
for city in City.query.filter_by(state_id=kwargs['obj'].city.state_id).order_by('name').all()]
但是这次没有设置城市默认值。我改变了这样的形式:
def __init__(self, *args, **kwargs):
kwargs['city'] = kwargs['obj'].city_id
super(UserEditForm, self).__init__(*args, **kwargs)
self.state.choices = [(state.id, state.name)
for state in State.query.order_by('name').all()]
self.city.choices = [(city.id, city.name)
for city in City.query.filter_by(state_id=kwargs['obj'].city.state_id).order_by('name').all()]
但它没有用。我尝试了很多解决方案,最后我将城市变量名称更改为 usercity:
usercity= SelectField("city", coerce=int)
和kwargs['city'] = kwargs['obj'].city_id
到kwargs['usercity'] = kwargs['obj'].city_id
。之后它工作正常。
问题是,当我设置时,城市选择字段的默认值从我在模型中定义的obj=user
读取。kwargs['obj'].city
user