Make handling of None values in forms clearer

If the browser posts the value of `<input value='None'>` to the server
it does so as a string.

We want to post a value of `None` (actually JSON `null`) to the API. To
do this we:
- set the value in the form class to `'None'` (ie a string)
- convert to `None` (as a type) afterwards

However seeing `x = 'None'` in code looks a bit like a mistake. So to
make sure it looks deliberate and clear what is happening this commit:
- makes a reusable constant for `'None'`
- adds a comment explaining why it’s a string
This commit is contained in:
Chris Hill-Scott
2018-11-12 09:04:39 +00:00
parent 74a4400bc7
commit c18a38d4f1
3 changed files with 26 additions and 9 deletions

View File

@@ -702,13 +702,25 @@ class ServicePostageForm(StripWhitespaceForm):
)
class RadioFieldWithNoneOption(RadioField):
class FieldWithNoneOption():
# This needs to match the data the browser will post from
# <input value='None'>
NONE_OPTION_VALUE = 'None'
def post_validate(self, form, validation_stopped):
if self.data == 'None':
if self.data == self.NONE_OPTION_VALUE:
self.data = None
class RadioFieldWithNoneOption(FieldWithNoneOption, RadioField):
pass
class HiddenFieldWithNoneOption(FieldWithNoneOption, HiddenField):
pass
class ServiceSetBranding(StripWhitespaceForm):
branding_style = RadioFieldWithNoneOption(
@@ -718,7 +730,7 @@ class ServiceSetBranding(StripWhitespaceForm):
]
)
DEFAULT = ('None', 'GOV.UK')
DEFAULT = (FieldWithNoneOption.NONE_OPTION_VALUE, 'GOV.UK')
def __init__(self, all_email_brandings, current_email_branding):
@@ -736,7 +748,7 @@ class ServiceSetBranding(StripWhitespaceForm):
class ServicePreviewBranding(StripWhitespaceForm):
branding_style = HiddenField('branding_style')
branding_style = HiddenFieldWithNoneOption('branding_style')
class GovernmentDomainField(StringField):
@@ -1124,7 +1136,7 @@ class TemplateAndFoldersSelectionForm(Form):
ALL_TEMPLATES_FOLDER = {
'name': 'All templates',
'id': 'None',
'id': RadioFieldWithNoneOption.NONE_OPTION_VALUE,
}
def __init__(