How do you set a default value for a WTForms SelectField?

后端 未结 7 635
-上瘾入骨i
-上瘾入骨i 2020-11-29 04:09

When attempting to set the default value of a SelectField with WTForms, I pass in value to the \'default\' parameter like so.

class TestForm(Form):
  test_fi         


        
7条回答
  •  悲哀的现实
    2020-11-29 04:55

    I have some problem with dynamic set default selectfield thati think can be useful. the model was like this:

    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')
    

    the form was like this:

    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()]   
    

    and the view was like this:

    @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)
         ....
    

    it works good and set Selectfield default value correctly. but i changed the code like this:

    in view:

    @dashboard.route('/useredit', methods=['GET', 'POST'])
        @login_required
        def useredit():
            ....
            user = current_user._get_current_object()       
            form = OrganEditForm(obj=user)
             ....
    

    in forms

    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()] 
    

    but this time the city default value doesn't set. i changed form like this:

    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()] 
    

    but it didn't work. I tried many solution and in the last I changed the city variable name to usercity:

    usercity= SelectField("city", coerce=int)
    

    and kwargs['city'] = kwargs['obj'].city_id to kwargs['usercity'] = kwargs['obj'].city_id. affter that it worked correctly.

    the problem was that when I set obj=user, default value for city selectfield read from kwargs['obj'].city that I defined in user model.

提交回复
热议问题