-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.py
80 lines (59 loc) · 1.82 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from dataclasses import dataclass
from typing import ClassVar
import validators
from flask import render_template_string
from flask_wtf import FlaskForm
from markupsafe import Markup
from peewee import Model
from wtforms.fields import Field
from wtforms.validators import ValidationError
class Renderable:
"""An object that can be rendered."""
def render(self) -> Markup:
"""Render template into :class:`Markup` object.
:return: rendering result as Markup
:rtype: Markup
"""
return Markup(render_template_string(self.template, obj=self))
@dataclass
class Link(Renderable):
href: str
text: str = 'klik'
template: ClassVar[str] = ''.join([
'<a href="{{ obj.href }}">',
'{{ obj.text }}',
'</a>',
])
@dataclass
class Button(Renderable):
type_: str = 'submit'
class_: str = 'primary'
icon: str = 'check'
icon_type: str = 'fas'
text: str = 'ok'
template: ClassVar[str] = ''.join([
'<button type="{{ obj.type_ }}" class="btn btn-{{ obj.class_ }}">',
'<i class="{{ obj.icon_type }} fa-{{ obj.icon }}"></i>',
' ',
'{{ obj.text }}',
'</button>',
])
class BaseForm(FlaskForm):
buttons = [
Button(text='zapisz'),
Link(href='javascript:history.back()', text='powrót'),
]
class ObjectForm(BaseForm):
def save(self, obj: Model, save: bool = True) -> Model:
self.populate_obj(obj)
if save:
obj.save()
return obj
class EmailValidator:
def __init__(self, message=None):
if message is None:
message = 'Nieprawidłowy adres email'
self.message = message
def __call__(self, form: FlaskForm, field: Field):
if not validators.email(field.data):
raise ValidationError(self.message)