How to make Flask-WTFoms update labels dynamically from list of label names?

前端 未结 2 995
萌比男神i
萌比男神i 2021-01-21 08:55

I use WTForms to define form for data filtering it is defined like this (My goal is to have user specified labels for BooleanFields set, I let each user to name labels for field

2条回答
  •  终归单人心
    2021-01-21 09:11

    Create a sample form as follows:

    from flask_wtf import FlaskForm
    from wtforms import StringField
    from wtforms.validators import DataRequired, Length
    from wtforms.fields import Label  #<==This is the key
    
    #in forms.py
    class MyForm(FlaskForm):
        name = StringField('Your Name', validators=[DataRequired(), Length(min=2, max=20)])
        submit = SubmitField('Sign Up')
    
    #in route.py
    from forms import MyForm
    #initialize your app
    
    @app.route("/some-test-route", methods = ["GET","POST"])
    def someTestRoute():
        form = MyForm
        if some condition:
            #change the label as follows.
            form.name.label = Label(field_id = "name", text = "Your New Field Description Goes Here.")
            #The above line creates the following lable object
            #
            #which replaces the current label object that is
            #
        if form.validate_on_submit():
            #do something
            return redirect(url_for(endpoint = "someEndPoint"))
        return render_template("WhereEverYour_MyForm_Template.html")
    

提交回复
热议问题