ScoDoc/app/forms/__init__.py

74 lines
1.9 KiB
Python
Raw Permalink Normal View History

"""WTF Forms for ScoDoc
"""
import re
from flask_wtf import FlaskForm
from wtforms import StringField, validators
class ScoDocForm(FlaskForm):
"""Super class for ScoDoc forms
(inspired by @iziram)
"""
def __init__(self, *args, **kwargs):
"Init form, adding a filed for our error messages"
super().__init__(*args, **kwargs)
self.ok = True
self.error_messages: list[str] = [] # used to report our errors
def set_error(self, err_msg, field=None):
"Set error message both in form and field"
self.ok = False
self.error_messages.append(err_msg)
if field:
field.errors.append(err_msg)
class ScoDateField(StringField):
"""A WTF field for date, using datepicker"""
def __init__(self, label: str, field_id: str, *args, **kwargs):
render_kw = {
"class": "datepicker",
"size": 10,
"id": field_id,
}
if "render_kw" in kwargs:
render_kw.update(kwargs["render_kw"])
super().__init__(
label,
validators=[validators.Length(max=10)],
render_kw=render_kw,
*args,
**kwargs
)
class ScoTimeField(StringField):
"""A WTF field for time, accept 12:34, 12h34, 12H34
Uses timepicker
"""
def __init__(self, label: str, field_id: str, *args, **kwargs):
render_kw = {
"class": "timepicker",
"size": 5,
"id": field_id,
}
if "render_kw" in kwargs:
render_kw.update(kwargs["render_kw"])
super().__init__(
label,
validators=[validators.Length(max=5)],
default="",
render_kw=render_kw,
filters=[
lambda x: (
re.sub(r"(^\d{2})[hH](\d{2}$)", r"\1:\2", x.strip()) if x else None
)
],
*args,
**kwargs
)