Skip to content

Commit

Permalink
refactor: use wtforms readonly validator
Browse files Browse the repository at this point in the history
  • Loading branch information
azmeuk committed Nov 21, 2023
1 parent bc56105 commit 3752693
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 20 deletions.
21 changes: 4 additions & 17 deletions canaille/app/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,31 +234,18 @@ def process_formdata(self, valuelist):
raise ValueError(self.gettext("Not a valid datetime value."))


class ReadOnly:
"""
Set a field readonly.
Validation fails if the form data is different than the
field object data, or if unset, from the field default data.
"""

def __init__(self):
self.field_flags = {"readonly": True}

def __call__(self, form, field):
if field.data and field.object_data and field.data != field.object_data:
raise wtforms.ValidationError(_("This field cannot be edited"))


def is_readonly(field):
return field.render_kw and "readonly" in field.render_kw


def set_readonly(field):
field.render_kw = field.render_kw or {}
field.render_kw["readonly"] = True
field.validators = list(field.validators) + [ReadOnly()]
field.validators = list(field.validators) + [wtforms.validators.ReadOnly()]


def set_writable(field):
del field.render_kw["readonly"]
field.validators = [v for v in field.validators if not isinstance(v, ReadOnly)]
field.validators = [
v for v in field.validators if not isinstance(v, wtforms.validators.ReadOnly)
]
6 changes: 3 additions & 3 deletions canaille/core/forms.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import wtforms.form
import wtforms.validators
from canaille.app import models
from canaille.app.forms import BaseForm
from canaille.app.forms import DateTimeUTCField
from canaille.app.forms import email_validator
from canaille.app.forms import Form
from canaille.app.forms import is_uri
from canaille.app.forms import phone_number
from canaille.app.forms import ReadOnly
from canaille.app.forms import set_readonly
from canaille.app.forms import unique_values
from canaille.app.i18n import lazy_gettext as _
Expand Down Expand Up @@ -337,7 +337,7 @@ class EditGroupForm(Form):
_("Name"),
validators=[
wtforms.validators.DataRequired(),
ReadOnly(),
wtforms.validators.ReadOnly(),
],
render_kw={
"readonly": "true",
Expand Down Expand Up @@ -400,7 +400,7 @@ class InvitationForm(Form):
class EmailConfirmationForm(Form):
old_emails = wtforms.FieldList(
wtforms.EmailField(
validators=[ReadOnly()],
validators=[wtforms.validators.ReadOnly()],
description=_(
"This email will be used as a recovery address to reset the password if needed"
),
Expand Down

0 comments on commit 3752693

Please sign in to comment.