Here are the examples of the python api django.forms.add_error taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1 Examples
0
Example 1
Project: nodewatcher Source File: base.py
@transaction.atomic(savepoint=False)
def prepare_root_forms(regpoint, request, root=None, data=None, save=False, form_state=None, flags=0):
"""
Prepares a list of configuration forms for use on a regpoint root's
configuration page.
:param regpoint: Registration point name or instance
:param request: Request instance
:param root: Registration point root instance for which to generate forms
:param data: User-supplied POST data
:param save: Are we performing a save or rendering an initial form
"""
# Ensure that all registry forms, form processors and CGMs are registered.
loader.load_modules('forms', 'formprocessors', 'cgm')
if save and flags & FORM_ONLY_DEFAULTS:
raise ValueError("You cannot use save and FORM_ONLY_DEFAULTS at the same time!")
if isinstance(regpoint, basestring):
regpoint = registration.point(regpoint)
# Transform data into a mutable dictionary in case an immutable one is passed
data = copy.copy(data)
# Prepare context
context = RegistryFormContext(
regpoint=regpoint,
request=request,
root=root,
data=data,
save=save,
validation_errors=False,
pending_save_forms={},
pending_save_foreign_keys={},
form_state=form_state,
flags=flags,
)
# Parse form actions.
if data:
form_actions = json.loads(data.get('ACTIONS', '{}'))
else:
form_actions = {}
for action, options in form_actions.items():
if action == 'defaults':
context.form_state.set_using_defaults(options['value'])
elif action == 'simple_mode':
# Simple mode should also automatically enable defaults.
if options['value']:
context.form_state.set_using_defaults(True)
if flags & FORM_SET_DEFAULTS:
context.form_state.set_using_defaults(flags & FORM_DEFAULTS_ENABLED)
if flags & FORM_INITIAL and flags & FORM_ROOT_CREATE and context.form_state.is_using_defaults():
# Set simple mode to its configured default value.
context.form_state.set_using_simple_mode(
getattr(settings, 'REGISTRY_SIMPLE_MODE', {}).get(regpoint.name, {}).get('default', False)
)
# Prepare form processors.
form_processors = []
for form_processor in regpoint.get_form_processors():
form_processor = form_processor()
form_processor.preprocess(root)
form_processors.append(form_processor)
try:
sid = transaction.savepoint()
forms = RootRegistryRenderItem(context, prepare_forms(context))
if flags & (FORM_DEFAULTS | FORM_ONLY_DEFAULTS):
# Apply form actions before applying defaults.
for action, options in form_actions.items():
if action == 'append':
context.form_state.append_default_item(options['registry_id'], options['parent_id'])
elif action == 'remove':
context.form_state.remove_item(options['index'])
elif action == 'simple_mode':
context.form_state.set_using_simple_mode(options['value'])
# Apply form defaults.
context.form_state.apply_form_defaults(regpoint, flags & FORM_ROOT_CREATE)
if flags & FORM_ONLY_DEFAULTS:
# If only defaults application is requested, we should set defaults and then rollback
# the savepoint in any case; all validation errors are ignored.
transaction.savepoint_rollback(sid)
return context.form_state
# Process forms when saving and there are no validation errors
if save and root is not None and not context.validation_errors:
# Resolve form dependencies and save all forms
for layer, linear_forms in enumerate(toposort.topological_sort(context.pending_save_forms)):
for info in linear_forms:
form = info['form']
# Before saving the form perform the validation again so dependent
# fields can be recalculated
form._clean_fields()
form._clean_form()
form._post_clean()
if form.is_valid():
# Save the form and store the instance into partial configuration so
# dependent objects can reference the new instance. Before we save,
# we also store the form's index into the display_order attribute of
# the instances, so that we preserve order when loading back from db.
form.instance.display_order = info['index']
instance = form.save()
# Only overwrite instances at the top layer (forms which have no dependencies
# on anything else). Models with dependencies will already be updated when
# calling save.
if layer == 0 and info['registry_id'] in context.form_state:
context.form_state[info['registry_id']][info['index']] = instance
for form_id, field in context.pending_save_foreign_keys.get(info['form_id'], []):
setattr(
context.pending_save_forms[form_id]['form'].instance,
field,
instance
)
else:
context.validation_errors = True
# Execute any validation hooks.
for processor in form_processors:
try:
processor.postprocess(root)
except RegistryValidationError, e:
context.validation_errors = True
forms.add_error(e.message)
if not context.validation_errors:
# Persist metadata.
regpoint.set_root_metadata(root, context.form_state.get_metadata())
root.save()
transaction.savepoint_commit(sid)
if flags & FORM_CLEAR_STATE:
context.form_state.clear_session()
else:
transaction.savepoint_rollback(sid)
except RegistryValidationError:
transaction.savepoint_rollback(sid)
except (transaction.TransactionManagementError, django_db.DatabaseError):
# Do not perform a rollback in case of a database error as this will just raise another
# database error exception as the transaction has been aborted.
raise
except:
transaction.savepoint_rollback(sid)
raise
return forms if not save else (context.validation_errors, forms)