如何使用Flask-AppBuilder使用自定义表单来更改选择字段的默认选择?

时间:2018-06-27 20:40:17

标签: python flask wtforms flask-appbuilder

将我的Flask应用更改为Flask-Appbuilder,并遇到一些问题。我想使用url中的参数来更改SelectField的默认选择,就像自动表单一样。通过以下配置,当选择第三座建筑物时,我在URL中获得“ / rooms / add?_flt_0_building = 3”。如何在WTForm中获取building_id以在页面上选择他?

房间形式:

class RoomForm(DynamicForm):
  building_list = db.session.query(Building).all()
  name = StringField('Room name', validators=[DataRequired()])
  building_id = SelectField('Building', choices=[(r.id, r.name) for r in building_list], validators=[DataRequired()])
  floor_id = StringField('Floor', validators=[DataRequired()])

房间型号:

class Room(Model):
  id = Column(Integer, primary_key=True)
  name = Column(String(80), unique=True, nullable=False)
  building_id = Column(Integer, ForeignKey('building.id'), nullable=False)
  building = relationship("Building")
  floors_id = Column(Integer, ForeignKey('floors.id'), nullable=True)
  floor = relationship("Floors")
  node = relationship('Nodes', backref='roomkey', lazy='dynamic')
  device = relationship('Devices', backref='roomkey2', lazy='dynamic')

  def __repr__(self):
    return self.name

class Building(Model):
  id = Column(Integer, primary_key=True)
  name = Column(String(80), unique=True, nullable=False)
  floors = Column(Integer)
  gunitbuilding = relationship('Room', backref='buildingkey', lazy='dynamic')

  def __repr__(self):
    return self.name
    return self.id

房间景观:

class Rooms(ModelView):
  datamodel = SQLAInterface(Room)
  show_title = 'Rooms'
  add_title = 'Add room'
  edit_title = 'Edit room'
  list_title = 'Rooms'
  list_columns = ['name']
  show_fieldsets = [('Summary', {'fields':['name']} )]
  search_columns = ['name']
  add_columns = ['name','building_id','floor_id']
  add_form = RoomForm

class managerooms(MasterDetailView):
  datamodel = SQLAInterface(Building)
  list_title = 'Buildings'
  list_columns = ['name']
  related_views = [Rooms]
  show_title = 'Buildings'

appbuilder.add_view_no_menu(managerooms)
appbuilder.add_view_no_menu(Rooms)
appbuilder.add_link("Rooms", href="/managerooms/list/1?next=%2Fmanagerooms%2Flist%2F1", icon="", category="Manage")

1 个答案:

答案 0 :(得分:0)

我想出了一种解决方法。如果有更好的方法,请告诉我。我在RoomForm中添加了refresh(),由于我不确定如何获取除完整URL,参数字符串以外的任何内容,因此我减去了前19个字符以获得正确的门牌号。

  def refresh():
    form = RoomForm()
    if request.method == 'GET':
      a=len(request.query_string)-19
      form.building_id.default = int(request.query_string[-a:])
      form.process()
    return form