5

Is it possible to make my form labels dynamic by passing an argument to the form constructor?

I'm thinking of something a bit like the following code:

class MyForm(Form):

    def __init__(self, fruit):
        Form.__init__(self)
        self.fruit = fruit

    name = StringField('Do you like' + fruit + "?")

@app.route('/' ,methods=["GET","POST"])
def home():
    form = NameForm("bananas")

Whatever I try, the text input box's label never seems to be able to access the variable 'fruit' - i.e. I can't seem to make the label dynamic.

It might just be that I don't understand Python objects well enough to see why this is not possible.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
RobinL
  • 11,009
  • 8
  • 48
  • 68
  • What do you mean by "you can't get it to work?" – Robert Harvey Jun 28 '14 at 17:40
  • I've tried to clarify the question with edits...thanks – RobinL Jun 28 '14 at 17:54
  • The form constructors are already defined and I guess you're looking to build your own overload, Python doesn't really handle overloads well (http://stackoverflow.com/questions/6434482/python-function-overloading). Sure it's doable but at the same time the dll for the form class is pretty annoying to access and inject code into (at least as far as I know but I'm a python scrub, but I guess that's one of the reasons why we get overloads in the other Visual languages). I would load the name from a source and then just set the name on the form.Text property instead. – Thomas Lindvall Jun 28 '14 at 19:03
  • Thanks Thomas. Glad I'm not missing something really obvious. I can solve it by rewriting the templates, this just (initially!) looked like a quick fix,,, – RobinL Jun 28 '14 at 19:12
  • Possible duplicate of [How to make Flask-WTFoms update labels dynamically from list of label names?](https://stackoverflow.com/questions/47480354/how-to-make-flask-wtfoms-update-labels-dynamically-from-list-of-label-names) – snakecharmerb Jun 30 '18 at 09:11

0 Answers0