Example #1
0
def patched_populate_obj(self, obj, name):
    """
    A patched version of flask_admin's Field.populate_obj().

    This patch is needed to:

    * treat an empty or whitespace-only string value as NULL (for
      pragmatic reasons: in many cases accepting such a string,
      typically being a result of a GUI user's mistake, would be just
      confusing; at the same time, we do not see any cases when
      accepting such strings could be useful);

    * append a list of validation errors -- if an n6-specific model's
      validator (not a Flask-Admin validator) raised an exception -- to
      highlight invalid fields values in the GUI view.

    """

    # treating empty or whitespace-only text as NULL
    to_be_set = (None if (isinstance(self.data, str) and not self.data.strip())
                 else self.data)

    # handling n6-specific model-level validation errors
    try:
        setattr(obj, name, to_be_set)
    except Exception as exc:
        invalid_field = getattr(exc, 'invalid_field', None)
        if invalid_field and isinstance(self.errors, MutableSequence):
            exc_message = get_exception_message(exc)
            if exc_message is not None:
                self.errors.append(exc_message)
            else:
                self.errors.append(u'Failed to create/update record.')
        raise
Example #2
0
def patched_populate_obj(self, obj, name):
    """
    Patch original method, in order to:
        * Prevent Flask-admin from populating fields with NoneType.
        * Append a list of validation errors, if a models' validator
          raised an exception (not Flask-Admin's validator), to
          highlight invalid field in application's view.
    """
    if self.data is not None:
        try:
            setattr(obj, name, self.data)
        except Exception as exc:
            invalid_field = getattr(exc, 'invalid_field', None)
            if invalid_field and isinstance(self.errors, MutableSequence):
                exc_message = get_exception_message(exc)
                if exc_message is not None:
                    self.errors.append(exc_message)
                else:
                    self.errors.append(u'Failed to create record.')
            raise
Example #3
0
    def test_get_exception_message_non_field_value_error_without_message(self):
        exc = NameError()
        exc_message = get_exception_message(exc)

        self.assertEqual(exc_message, None)
Example #4
0
    def test_get_exception_message_non_field_value_error_empty_message_string(
            self):
        exc = NameError("")
        exc_message = get_exception_message(exc)

        self.assertEqual(exc_message, None)
Example #5
0
    def test_get_exception_message_field_value_error(self):
        exc = FieldValueError(
            public_message='Example FieldValueError message.')
        exc_message = get_exception_message(exc)

        self.assertEqual(exc_message, 'Example FieldValueError message.')