Get rid of newstyle flag for Form.validate() method

we always/only use "new style" now
This commit is contained in:
Lance Edgar 2023-05-14 20:28:48 -05:00
parent a991dc0684
commit 85947878c4
17 changed files with 75 additions and 72 deletions

View file

@ -407,7 +407,7 @@ class ReceivingBatchRowViews(APIBatchRowView):
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
# TODO: this seems hacky, but avoids "complex" date value parsing # TODO: this seems hacky, but avoids "complex" date value parsing
form.set_widget('expiration_date', dfwidget.TextInputWidget()) form.set_widget('expiration_date', dfwidget.TextInputWidget())
if not form.validate(newstyle=True): if not form.validate():
log.debug("form did not validate: %s", log.debug("form did not validate: %s",
form.make_deform_form().error) form.make_deform_form().error)
return {'error': "Form did not validate"} return {'error': "Form did not validate"}

View file

@ -89,7 +89,7 @@ class CommonView(APIView):
# identical; perhaps should merge somehow? # identical; perhaps should merge somehow?
schema = Feedback().bind(session=Session()) schema = Feedback().bind(session=Session())
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
if form.validate(newstyle=True): if form.validate():
data = dict(form.validated) data = dict(form.validated)
# figure out who the sending user is, if any # figure out who the sending user is, if any

View file

@ -26,6 +26,7 @@ Forms Core
import json import json
import logging import logging
import warnings
from collections import OrderedDict from collections import OrderedDict
import sqlalchemy as sa import sqlalchemy as sa
@ -1167,49 +1168,51 @@ class Form(object):
return self.defaults[field_name] return self.defaults[field_name]
def validate(self, *args, **kwargs): def validate(self, *args, **kwargs):
if kwargs.pop('newstyle', False): """
# yay, new behavior! Try to validate the form.
if hasattr(self, 'validated'):
del self.validated
if self.request.method != 'POST':
return False
controls = get_form_data(self.request).items() This should work whether data was submitted as classic POST
data, or as JSON body.
# unfortunately the normal form logic (i.e. peppercorn) is :returns: ``True`` if form data is valid, otherwise ``False``.
# expecting all values to be strings, whereas if our data """
# came from JSON body, may have given us some Pythonic if 'newstyle' in kwargs:
# objects. so here we must convert them *back* to strings warnings.warn("the `newstyle` kwarg is no longer used "
# TODO: this seems like a hack, i must be missing something "for Form.validate()",
# TODO: also this uses same "JSON" check as get_form_data() DeprecationWarning, stacklevel=2)
if self.request.is_xhr and not self.request.POST:
controls = [[key, val] for key, val in controls]
for i in range(len(controls)):
key, value = controls[i]
if value is None:
controls[i][1] = ''
elif value is True:
controls[i][1] = 'true'
elif value is False:
controls[i][1] = 'false'
elif not isinstance(value, str):
controls[i][1] = str(value)
dform = self.make_deform_form() if hasattr(self, 'validated'):
try: del self.validated
self.validated = dform.validate(controls) if self.request.method != 'POST':
return True return False
except deform.ValidationFailure:
return False
else: # legacy behavior controls = get_form_data(self.request).items()
raise_error = kwargs.pop('raise_error', True)
dform = self.make_deform_form() # unfortunately the normal form logic (i.e. peppercorn) is
try: # expecting all values to be strings, whereas if our data
return dform.validate(*args, **kwargs) # came from JSON body, may have given us some Pythonic
except deform.ValidationFailure: # objects. so here we must convert them *back* to strings
if raise_error: # TODO: this seems like a hack, i must be missing something
raise # TODO: also this uses same "JSON" check as get_form_data()
if self.request.is_xhr and not self.request.POST:
controls = [[key, val] for key, val in controls]
for i in range(len(controls)):
key, value = controls[i]
if value is None:
controls[i][1] = ''
elif value is True:
controls[i][1] = 'true'
elif value is False:
controls[i][1] = 'false'
elif not isinstance(value, str):
controls[i][1] = str(value)
dform = self.make_deform_form()
try:
self.validated = dform.validate(controls)
return True
except deform.ValidationFailure:
return False
class FieldList(list): class FieldList(list):

View file

@ -105,7 +105,7 @@ class AuthenticationView(View):
form.auto_disable = False # TODO: deprecate / remove this form.auto_disable = False # TODO: deprecate / remove this
form.show_reset = True form.show_reset = True
form.show_cancel = False form.show_cancel = False
if form.validate(newstyle=True): if form.validate():
user = self.authenticate_user(form.validated['username'], user = self.authenticate_user(form.validated['username'],
form.validated['password']) form.validated['password'])
if user: if user:
@ -185,7 +185,7 @@ class AuthenticationView(View):
schema = ChangePassword().bind(user=self.request.user, request=self.request) schema = ChangePassword().bind(user=self.request.user, request=self.request)
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
if form.validate(newstyle=True): if form.validate():
set_user_password(self.request.user, form.validated['new_password']) set_user_password(self.request.user, form.validated['new_password'])
self.request.session.flash("Your password has been changed.") self.request.session.flash("Your password has been changed.")
return self.redirect(self.request.get_referrer()) return self.redirect(self.request.get_referrer())

View file

@ -566,7 +566,7 @@ class BatchMasterView(MasterView):
self.request.session.flash("Request ignored, since batch has already been executed") self.request.session.flash("Request ignored, since batch has already been executed")
else: else:
form = forms.Form(schema=ToggleComplete(), request=self.request) form = forms.Form(schema=ToggleComplete(), request=self.request)
if form.validate(newstyle=True): if form.validate():
if form.validated['complete']: if form.validated['complete']:
self.mark_batch_complete(batch) self.mark_batch_complete(batch)
else: else:
@ -1273,7 +1273,7 @@ class BatchMasterView(MasterView):
batch = self.get_instance() batch = self.get_instance()
self.executing = True self.executing = True
form = self.make_execute_form(batch) form = self.make_execute_form(batch)
if form.validate(newstyle=True): if form.validate():
kwargs = dict(form.validated) kwargs = dict(form.validated)
# cache options to use as defaults next time # cache options to use as defaults next time
@ -1344,7 +1344,7 @@ class BatchMasterView(MasterView):
indicator page. indicator page.
""" """
form = self.make_execute_form() form = self.make_execute_form()
if form.validate(newstyle=True): if form.validate():
kwargs = dict(form.validated) kwargs = dict(form.validated)
# cache options to use as defaults next time # cache options to use as defaults next time

View file

@ -234,7 +234,7 @@ class InventoryBatchView(BatchMasterView):
schema = DesktopForm().bind(session=self.Session()) schema = DesktopForm().bind(session=self.Session())
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
if self.request.method == 'POST': if self.request.method == 'POST':
if form.validate(newstyle=True): if form.validate():
product = self.Session.get(model.Product, form.validated['product']) product = self.Session.get(model.Product, form.validated['product'])

View file

@ -161,7 +161,7 @@ class CommonView(View):
model = self.model model = self.model
schema = Feedback().bind(session=Session()) schema = Feedback().bind(session=Session())
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
if form.validate(newstyle=True): if form.validate():
data = dict(form.validated) data = dict(form.validated)
if data['user']: if data['user']:
data['user'] = Session.get(model.User, data['user']) data['user'] = Session.get(model.User, data['user'])

View file

@ -62,7 +62,7 @@ class GenerateFeatureView(View):
result = rendered_result = None result = rendered_result = None
feature_type = 'new-report' feature_type = 'new-report'
if self.request.method == 'POST': if self.request.method == 'POST':
if app_form.validate(newstyle=True): if app_form.validate():
feature_type = self.request.POST['feature_type'] feature_type = self.request.POST['feature_type']
feature = self.handler.get_feature(feature_type) feature = self.handler.get_feature(feature_type)
@ -70,7 +70,7 @@ class GenerateFeatureView(View):
raise ValueError("Unknown feature type: {}".format(feature_type)) raise ValueError("Unknown feature type: {}".format(feature_type))
feature_form = feature_forms[feature.feature_key] feature_form = feature_forms[feature.feature_key]
if feature_form.validate(newstyle=True): if feature_form.validate():
context = dict(app_form.validated) context = dict(app_form.validated)
context.update(feature_form.validated) context.update(feature_form.validated)
result = self.handler.do_generate(feature, **context) result = self.handler.do_generate(feature, **context)

View file

@ -723,7 +723,7 @@ class MasterView(View):
form = forms.Form(schema=schema, request=self.request) form = forms.Form(schema=schema, request=self.request)
form.save_label = "Upload" form.save_label = "Upload"
form.cancel_url = self.get_index_url() form.cancel_url = self.get_index_url()
if form.validate(newstyle=True): if form.validate():
uploads = self.normalize_uploads(form) uploads = self.normalize_uploads(form)
filepath = uploads['filename']['temp_path'] filepath = uploads['filename']['temp_path']
@ -1408,7 +1408,7 @@ class MasterView(View):
pass pass
def validate_quick_row_form(self, form): def validate_quick_row_form(self, form):
return form.validate(newstyle=True) return form.validate()
def make_default_row_grid_tools(self, obj): def make_default_row_grid_tools(self, obj):
if self.rows_creatable: if self.rows_creatable:
@ -2301,7 +2301,7 @@ class MasterView(View):
factory = self.get_form_factory() factory = self.get_form_factory()
form = factory(schema=schema, request=self.request) form = factory(schema=schema, request=self.request)
if not form.validate(newstyle=True): if not form.validate():
return {'error': "Form did not validate"} return {'error': "Form did not validate"}
# nb. self.Session may differ, so use tailbone.db.Session # nb. self.Session may differ, so use tailbone.db.Session
@ -2334,7 +2334,7 @@ class MasterView(View):
factory = self.get_form_factory() factory = self.get_form_factory()
form = factory(schema=schema, request=self.request) form = factory(schema=schema, request=self.request)
if not form.validate(newstyle=True): if not form.validate():
return {'error': "Form did not validate"} return {'error': "Form did not validate"}
# nb. self.Session may differ, so use tailbone.db.Session # nb. self.Session may differ, so use tailbone.db.Session
@ -4057,7 +4057,7 @@ class MasterView(View):
supp.configure_form(form) supp.configure_form(form)
def validate_form(self, form): def validate_form(self, form):
if form.validate(newstyle=True): if form.validate():
self.form_deserialized = form.validated self.form_deserialized = form.validated
return True return True
return False return False
@ -4514,7 +4514,7 @@ class MasterView(View):
self.configure_field_product_key(form) self.configure_field_product_key(form)
def validate_row_form(self, form): def validate_row_form(self, form):
if form.validate(newstyle=True): if form.validate():
self.form_deserialized = form.validated self.form_deserialized = form.validated
return True return True
return False return False

View file

@ -1000,7 +1000,7 @@ class PersonView(MasterView):
def profile_add_note(self): def profile_add_note(self):
person = self.get_instance() person = self.get_instance()
form = self.make_note_form('create', person) form = self.make_note_form('create', person)
if form.validate(newstyle=True): if form.validate():
note = self.create_note(person, form) note = self.create_note(person, form)
self.Session.flush() self.Session.flush()
return self.profile_add_note_success(note) return self.profile_add_note_success(note)
@ -1025,7 +1025,7 @@ class PersonView(MasterView):
def profile_edit_note(self): def profile_edit_note(self):
person = self.get_instance() person = self.get_instance()
form = self.make_note_form('edit', person) form = self.make_note_form('edit', person)
if form.validate(newstyle=True): if form.validate():
note = self.update_note(person, form) note = self.update_note(person, form)
self.Session.flush() self.Session.flush()
return self.profile_edit_note_success(note) return self.profile_edit_note_success(note)
@ -1047,7 +1047,7 @@ class PersonView(MasterView):
def profile_delete_note(self): def profile_delete_note(self):
person = self.get_instance() person = self.get_instance()
form = self.make_note_form('delete', person) form = self.make_note_form('delete', person)
if form.validate(newstyle=True): if form.validate():
self.delete_note(person, form) self.delete_note(person, form)
self.Session.flush() self.Session.flush()
return self.profile_delete_note_success(person) return self.profile_delete_note_success(person)

View file

@ -1972,7 +1972,7 @@ class ProductView(MasterView):
params_forms[key] = forms.Form(schema=schema, request=self.request) params_forms[key] = forms.Form(schema=schema, request=self.request)
if self.request.method == 'POST': if self.request.method == 'POST':
if form.validate(newstyle=True): if form.validate():
data = form.validated data = form.validated
fully_validated = True fully_validated = True
@ -1985,7 +1985,7 @@ class ProductView(MasterView):
# collect batch-type-specific params # collect batch-type-specific params
pform = params_forms.get(batch_key) pform = params_forms.get(batch_key)
if pform: if pform:
if pform.validate(newstyle=True): if pform.validate():
pdata = pform.validated pdata = pform.validated
for field in pform.schema: for field in pform.schema:
param_name = pform.schema[field.name].param_name param_name = pform.schema[field.name].param_name

View file

@ -65,7 +65,7 @@ class GeneratedProjectView(MasterView):
project_type = self.request.matchdict.get('project_type') project_type = self.request.matchdict.get('project_type')
if project_type: if project_type:
form = self.make_project_form(project_type) form = self.make_project_form(project_type)
if form.validate(newstyle=True): if form.validate():
zipped = self.generate_project(project_type, form) zipped = self.generate_project(project_type, form)
return self.file_response(zipped) return self.file_response(zipped)
@ -83,7 +83,7 @@ class GeneratedProjectView(MasterView):
# if form validates, then user has chosen a project type, so # if form validates, then user has chosen a project type, so
# we redirect to the appropriate "generate project" page # we redirect to the appropriate "generate project" page
if form.validate(newstyle=True): if form.validate():
raise self.redirect(self.request.route_url( raise self.redirect(self.request.route_url(
'generate_specific_project', 'generate_specific_project',
project_type=form.validated['project_type'])) project_type=form.validated['project_type']))

View file

@ -225,7 +225,7 @@ class CostingBatchView(PurchasingBatchView):
# if form validates, that means user has chosen a creation type, so we # if form validates, that means user has chosen a creation type, so we
# just redirect to the appropriate "new batch of type X" page # just redirect to the appropriate "new batch of type X" page
if form.validate(newstyle=True): if form.validate():
workflow_key = form.validated['workflow'] workflow_key = form.validated['workflow']
vendor_uuid = form.validated['vendor'] vendor_uuid = form.validated['vendor']
url = self.request.route_url('{}.create_workflow'.format(route_prefix), url = self.request.route_url('{}.create_workflow'.format(route_prefix),

View file

@ -358,7 +358,7 @@ class ReceivingBatchView(PurchasingBatchView):
# if form validates, that means user has chosen a creation type, so we # if form validates, that means user has chosen a creation type, so we
# just redirect to the appropriate "new batch of type X" page # just redirect to the appropriate "new batch of type X" page
if form.validate(newstyle=True): if form.validate():
workflow_key = form.validated['workflow'] workflow_key = form.validated['workflow']
vendor_uuid = form.validated['vendor'] vendor_uuid = form.validated['vendor']
url = self.request.route_url('{}.create_workflow'.format(route_prefix), url = self.request.route_url('{}.create_workflow'.format(route_prefix),
@ -1196,7 +1196,7 @@ class ReceivingBatchView(PurchasingBatchView):
# TODO: what is this one about again? # TODO: what is this one about again?
form.remove_field('quick_receive') form.remove_field('quick_receive')
if form.validate(newstyle=True): if form.validate():
# handler takes care of the row receiving logic for us # handler takes care of the row receiving logic for us
kwargs = dict(form.validated) kwargs = dict(form.validated)
@ -1382,7 +1382,7 @@ class ReceivingBatchView(PurchasingBatchView):
# expiration_date # expiration_date
form.set_type('expiration_date', 'date_jquery') form.set_type('expiration_date', 'date_jquery')
if form.validate(newstyle=True): if form.validate():
# handler takes care of the row receiving logic for us # handler takes care of the row receiving logic for us
kwargs = dict(form.validated) kwargs = dict(form.validated)

View file

@ -373,7 +373,7 @@ class ReportOutputView(ExportMasterView):
# if form validates, that means user has chosen a report type, so we # if form validates, that means user has chosen a report type, so we
# just redirect to the appropriate "new report" page # just redirect to the appropriate "new report" page
if form.validate(newstyle=True): if form.validate():
raise self.redirect(self.request.route_url('generate_specific_report', raise self.redirect(self.request.route_url('generate_specific_report',
type_key=form.validated['report_type'])) type_key=form.validated['report_type']))
@ -465,7 +465,7 @@ class ReportOutputView(ExportMasterView):
form.set_default(param.name, value) form.set_default(param.name, value)
# if form validates, start generating new report output; show progress page # if form validates, start generating new report output; show progress page
if form.validate(newstyle=True): if form.validate():
key = 'report_output.generate' key = 'report_output.generate'
progress = self.make_progress(key) progress = self.make_progress(key)
kwargs = {'progress': progress} kwargs = {'progress': progress}

View file

@ -274,7 +274,7 @@ class AppSettingsView(View):
form = self.make_form(settings) form = self.make_form(settings)
form.cancel_url = self.request.current_route_url() form.cancel_url = self.request.current_route_url()
if form.validate(newstyle=True): if form.validate():
self.save_form(form) self.save_form(form)
group = self.request.POST.get('settings-group') group = self.request.POST.get('settings-group')
if group is not None: if group is not None:

View file

@ -164,7 +164,7 @@ class TimeSheetView(View):
Process a "shift filter" form if one was in fact POST'ed. If it was Process a "shift filter" form if one was in fact POST'ed. If it was
then we store new context in session and redirect to display as normal. then we store new context in session and redirect to display as normal.
""" """
if form.validate(newstyle=True): if form.validate():
store = form.validated['store'] store = form.validated['store']
self.request.session['timesheet.{}.store'.format(self.key)] = store.uuid if store else None self.request.session['timesheet.{}.store'.format(self.key)] = store.uuid if store else None
department = form.validated['department'] department = form.validated['department']
@ -178,7 +178,7 @@ class TimeSheetView(View):
Process an "employee shift filter" form if one was in fact POST'ed. If it Process an "employee shift filter" form if one was in fact POST'ed. If it
was then we store new context in session and redirect to display as normal. was then we store new context in session and redirect to display as normal.
""" """
if form.validate(newstyle=True): if form.validate():
employee = form.validated['employee'] employee = form.validated['employee']
self.request.session['timesheet.{}.employee'.format(self.key)] = employee.uuid if employee else None self.request.session['timesheet.{}.employee'.format(self.key)] = employee.uuid if employee else None
date = form.validated['date'] date = form.validated['date']