Pass variable to Python Flask form
You can solve this problem by using the global context variable g
. The trick is not to use the builtin validator but a custom validator. The reason is that the builtin validator is a factory function. This means the validationMessage
function you pass to it will only be executed on class creation. If you build a custom validator and read the language
from the global context variable it will work.
def custom_validator(form, field): language = g.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 if not len(field.data): raise validators.ValidationError(text)
Replace the validator in your form with the custom validator:
class messageForm(FlaskForm): title = StringField('title', validators=[custom_validator])
In the view function just create the language property for the global context variable.
# Messages@admin.route('/<string:language>/message', methods=['GET'])def messageView(language='dk') g.language = language form=messageForm() ...