I'm currently stuck trying to build a variable message flashing function for my Flask forms
Since I'm building a tool that has to have multiple languages available, I wish to create custom messages for my flask form validation based on specific language input.
My form looks something like this:
class messageForm(FlaskForm):
title = StringField(
'title',
validators=[
validators.DataRequired(validationMessage('validateRequired', language=language))
]
)
the function "validationMessage" looks like this:
def validationMessage(message, language):
msg = Message.query.filter_by(title=message).first()
lang = Language.query.filter_by(abbr=language).first()
text = messageBody.query.filter_by(message_id=msg.id, language_id=lang.id).first().text
return text
As you notice, I do some lookup in a few database tables to produce my message text.
My trouble is now... How do I pass my language variable from my view to my form so that I can pass it on to the "validationMessage" function?
The language variable is based on a variable in my view endpoint
# Messages
@admin.route('/<string:language>/message', methods=['GET'])
def messageView(language='dk')
form=messageForm()
...
I have considered using my session for this, but as I understand it, I can only use this within my view and therefore not within either my form or the message function
HiddenFieldcalledlang, your form could be instantiated asform=messageForm(lang=language). Then set the validatorslanguageargument to be the value of yourHiddenFieldvalidationMessagefunction only gets called when initializing your validator. And that happens right when you start your Flask app. It is not called later on form validation anymore. So this approach won't work at all.