-
Notifications
You must be signed in to change notification settings - Fork 174
/
forms.py
88 lines (71 loc) · 2.93 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
81
82
83
84
85
86
87
88
from __future__ import annotations
from typing import Any, Generator, Tuple, Union
import markupsafe
from sanic.log import logger
from sanic_wtf import SanicForm as _SanicForm
from wtforms import (
BooleanField, PasswordField, SelectField,
SelectMultipleField, StringField, SubmitField, TextAreaField
)
from wtforms.validators import DataRequired
from wtforms.widgets import HiddenInput
class SwitchField(SelectField):
...
class SanicForm(_SanicForm):
def hidden_tag(self, *fields):
def hidden_fields(
fields: Union[Tuple[Any, ...], SanicForm]) -> Generator:
for f in fields:
if isinstance(f, str):
f = getattr(self, f, None)
if f is None or not isinstance(f.widget, HiddenInput):
continue
yield f
return markupsafe.Markup(
u'\n'.join(str(f) for f in hidden_fields(fields or self))
)
def validate(self) -> bool:
extra_validators = {}
for name in self._fields:
if (inline := getattr(self.__class__, 'validate_%s' % name,
None)) is not None:
extra_validators[name] = [inline]
self._errors = None
success = True
for name, field in self._fields.items():
if field.type in ('SelectField', 'SelectMultipleField'):
continue
if extra_validators is not None and name in extra_validators:
extra = extra_validators[name]
else:
extra = list()
if not field.validate(self, extra):
success = False
logger.info(f'[Validate Fail] {field}')
return success
class UserForm(SanicForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
avatar = StringField('Email', default='')
password = PasswordField('Password')
active = BooleanField('Active')
submit = SubmitField('Submit')
class PostForm(SanicForm):
title = StringField('Title', validators=[DataRequired()])
slug = StringField('Slug')
summary = StringField('Summary')
content = TextAreaField('Content', default='')
can_comment = BooleanField('CanComment', default=True)
tags = SelectMultipleField('Tags', default=[])
status = SwitchField('Published', choices=[0, 1], default=1, coerce=int)
is_page = BooleanField('IsPage', default=False)
target_title = StringField('TargetTitle')
target_url = StringField('TargetURL')
target_abstract = StringField('TargetAbstract')
target_basename = StringField('TargetBaseName')
submit = SubmitField('Submit')
class TopicForm(SanicForm):
slug = StringField('Slug')
intro = StringField('Intro', validators=[DataRequired()])
title = StringField('Title', validators=[DataRequired()])
status = SwitchField('Published', choices=[0, 1], default=1, coerce=int)