Last active
March 28, 2024 11:44
-
-
Save dukebody/dcc371bf286534d546e9 to your computer and use it in GitHub Desktop.
JSON field for WTForms that converts between the form string data and a dictionary representation, with validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from wtforms import fields | |
import json | |
class JSONField(fields.StringField): | |
def _value(self): | |
return json.dumps(self.data) if self.data else '' | |
def process_formdata(self, valuelist): | |
if valuelist: | |
try: | |
self.data = json.loads(valuelist[0]) | |
except ValueError: | |
raise ValueError('This field contains invalid JSON') | |
else: | |
self.data = None | |
def pre_validate(self, form): | |
super().pre_validate(form) | |
if self.data: | |
try: | |
json.dumps(self.data) | |
except TypeError: | |
raise ValueError('This field contains invalid JSON') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment