Example #1
0
 def clean(self, value):
     value = super(IPAddrField, self).clean(value)
     errors = []
     result = []
     for line in StringIO(value):
         ip = line.replace('\n','').strip()
         if ip:
             try:
                 ipaddress.ip_address(ip)
                 result.append(ip)
             except ValueError as e:
                 errors.append(str(e))
     if errors:
         raise ValidationError(errors)
     return result
Example #2
0
def validate_editable_entities(entities, user, code='changenotallowed'):
    validate_authenticated_user(
        user,
        ugettext_lazy(
            u'Not authenticated user is not allowed to edit entities'), code)

    has_perm = user.has_perm_to_change
    uneditable = entities2unicode((e for e in entities if not has_perm(e)),
                                  user)

    if uneditable:
        raise ValidationError(
            _(u'Some entities are not editable: {}').format(uneditable),
            code=code)

    return entities
Example #3
0
def validate_linkable_model(model, user, owner, code='linknotallowed'):
    validate_authenticated_user(
        user,
        ugettext_lazy(
            u'Not authenticated user is not allowed to link «{model}»'),
        code=code,
        model=model._meta.verbose_name_plural)

    if not user.has_perm_to_link(model, owner=owner):
        raise ValidationError(
            _(u'You are not allowed to link with the «{models}» of this user.'
              ).format(models=model._meta.verbose_name_plural, ),
            code=code,
        )

    return owner
Example #4
0
    def clean(self):
        """
        This method insures atleast a single correct answer is marked for a
        Question while creating a test, if not it raises Validation Error.
        :return:
        """
        super().clean()

        has_one_correct_answer = False
        for form in self.forms:
            if not form.cleaned_data.get('DELETE', False):
                if form.cleaned_data.get('is_correct', False):
                    has_one_correct_answer = True
                    break
        if not has_one_correct_answer:
            raise ValidationError('Mark at least one answer as correct.',
                                  code='no_correct_answer')
Example #5
0
 def pre_init(self, value, obj):
     """Convert a string value to JSON only if it needs to be deserialized.
     SubfieldBase metaclass has been modified to call this method instead of
     to_python so that we can check the obj state and determine if it needs to be
     deserialized
     """
     try:
         if obj._state.adding:
             if getattr(obj, "pk", None) is not None:
                 if isinstance(value, six.string_types):
                     try:
                         return json.loads(value, **self.load_kwargs)
                     except ValueError:
                         raise ValidationError(_("Enter valid JSON"))
     except AttributeError:
         pass
     return value
Example #6
0
    def clean_password_2(self):
        get_data = self.cleaned_data.get
        password1 = get_data('password_1')
        password2 = get_data('password_2')

        if password1 and password2 and password1 != password2:
            raise ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )

        # user = self.instance
        # user.username = get_data('username')
        #
        # password_validation.validate_password(password2, user)

        return password2
Example #7
0
    def clean_email_field(self):
        data = self.cleaned_data['email_field']

        # Set our instance on the basis of the email field, or raise
        # a validationerror
        try:
            self.instance = Subscription.objects.get(
                newsletter=self.instance.newsletter,
                email_field__exact=data
            )

        except Subscription.DoesNotExist:
                raise ValidationError(
                    _("This e-mail address has not been subscribed to.")
                )

        return data
Example #8
0
    def pre_init(self, value, obj):
        """Convert a string value to JSON only if it needs to be deserialized.
        SubfieldBase metaclass has been modified to call this method instead of
        to_python so that we can check the obj state and determine if it needs to be
        deserialized"""

        if obj._state.adding:
            # Make sure the primary key actually exists on the object before
            # checking if it's empty. This is a special case for South datamigrations
            # see: https://github.com/bradjasper/django-jsonfield/issues/52
            if getattr(obj, "pk", None) is not None:
                if isinstance(value, six.string_types):
                    try:
                        return json.loads(value, **self.load_kwargs)
                    except ValueError:
                        raise ValidationError(_("Enter valid JSON"))

        return value
Example #9
0
def validate_viewable_entities(entities, user, code='viewnotallowed'):
    validate_authenticated_user(
        user,
        gettext_lazy('Not authenticated user is not allowed to view entities'),
        code,
    )

    has_perm = user.has_perm_to_view
    unviewable = entities_to_str((e for e in entities if not has_perm(e)),
                                 user)

    if unviewable:
        raise ValidationError(
            _('Some entities are not viewable: {}').format(unviewable),
            code=code,
        )

    return entities
Example #10
0
    def _clean_parameter(self, data, graph_type: int):
        validator = self.constraint_registry.get_parameter_validator(
            graph_type)

        if validator:
            value = data.get('parameter')

            try:
                parameter = validator.clean(value)
            except ValidationError as e:
                raise ValidationError(
                    self.error_messages['invalidparameter'].format(e.message),
                    code='invalidparameter',
                ) from e
        else:
            # TODO: validate data is empty
            parameter = None

        return parameter
Example #11
0
 def clean(self):
     if any(self.errors):
         # Don't bother validating the formset unless each form is valid on its own
         return
     staffings = []
     for form in self.forms:
         if form.cleaned_data.get("detail_type",
                                  "") != "TIME_SPENT_MISSION":
             continue
         staffing = [
             form.cleaned_data['mission'].id,
             form.cleaned_data['month'].toordinal(),
             form.cleaned_data["consultant"].id
         ]
         if staffing in staffings:
             raise ValidationError(
                 _("Cannot declare twice the same consultant for the same mission on a given month"
                   ))
         staffings.append(staffing)
Example #12
0
    def clean_email_field(self):
        data = self.cleaned_data['email_field']

        # Check whether we have already been subscribed to
        try:
            subscription = Subscription.objects.get(
                email_field__exact=data, newsletter=self.instance.newsletter)

            if subscription.subscribed and not subscription.unsubscribed:
                raise ValidationError(
                    _("Your e-mail address has already been subscribed to."))
            else:
                self.instance = subscription

            self.instance = subscription

        except Subscription.DoesNotExist:
            pass

        return data
Example #13
0
    def pre_init(self, value, obj):
        """Convert a string value to JSON only if it needs to be deserialized.
        SubfieldBase metaclass has been modified to call this method instead of
        to_python so that we can check the obj state and determine if it needs to be
        deserialized"""

        try:
            if obj._state.adding:
                if isinstance(value, six.string_types):
                    try:
                        return json.loads(value, **self.load_kwargs)
                    except ValueError:
                        raise ValidationError(_("Enter valid JSON"))

        except AttributeError:
            # south fake meta class doesn't create proper attributes
            # see this:
            # https://github.com/bradjasper/django-jsonfield/issues/52
            pass

        return value
Example #14
0
    def _value_from_unjsonfied(self, data):
        aggr_id = self._clean_aggr_id(data)
        if not aggr_id:
            return None

        constraint = self.constraint_registry.get_constraint_by_aggr_id(
            model=self.model,
            aggr_id=aggr_id,
        )
        if constraint is None:
            raise ValidationError(
                self.error_messages['aggridinvalid'],
                code='aggridinvalid',
            )

        cell = self._clean_cell(data, constraint)

        return OrdinateInfo(
            aggr_id=aggr_id,
            cell=cell,
        )
Example #15
0
def save_image_file(image_data, result, related_data_form):
    """Saves an uploaded image file stream to its final destination in the blob
    store.  If the given result has already an image connected with it, it is
    removed first.

    :param image_data: the file-like object which contains the uploaded data
        stream
    :param result: The result object for which the image was uploaded.  It is
        not necessary that all its fields are already there.  But it must have
        been written already to the database because the only necessary field
        is the primary key, which I need for the hash digest for generating the
        file names.
    :param related_data_form: A bound form with the image filename that was
        uploaded.  This is only needed for dumping error messages into it if
        something went wrong.

    :type image_data: ``django.core.files.uploadedfile.UploadedFile``
    :type result: `models.Result`
    :type related_data_form: `RelatedDataForm`
    """
    for i, chunk in enumerate(image_data.chunks()):
        if i == 0:
            if chunk.startswith(b"\211PNG\r\n\032\n"):
                new_image_type = "png"
            elif chunk.startswith(b"\xff\xd8\xff"):
                new_image_type = "jpeg"
            elif chunk.startswith(b"%PDF"):
                new_image_type = "pdf"
            else:
                related_data_form.add_error("image_file", ValidationError(
                    _("Invalid file format.  Only PDF, PNG, and JPEG are allowed."), code="invalid"))
                return
            if result.image_type != "none" and new_image_type != result.image_type:
                jb_common.utils.blobs.storage.unlink(result.get_image_locations()["image_file"])
            result.image_type = new_image_type
            image_path = result.get_image_locations()["image_file"]
            destination = jb_common.utils.blobs.storage.open(image_path, "w")
        destination.write(chunk)
    destination.close()
    result.save()
Example #16
0
 def clean(self):
     cleaned_data = super(OriginalDataForm, self).clean()
     if "new_name" in cleaned_data:
         new_name = cleaned_data["new_name"]
         sample = cleaned_data.get("sample")
         if sample and not sample_names.valid_new_sample_name(sample.name, new_name) and \
            not new_name.startswith(sample.name):
             error_message = _("The new name must begin with the old name.")
             params = {}
             old_sample_name_format = sample_names.sample_name_format(sample.name)
             possible_new_name_formats = \
                     settings.SAMPLE_NAME_FORMATS[old_sample_name_format].get("possible_renames", set())
             if possible_new_name_formats:
                 error_message += ungettext("  Alternatively, it must be a valid “%(sample_formats)s” name.",
                                            "  Alternatively, it must be a valid name of one of these types: "
                                            "%(sample_formats)s.", len(possible_new_name_formats))
                 params.update({"sample_formats": format_enumeration(
                     sample_names.verbose_sample_name_format(name_format) for name_format in possible_new_name_formats)})
             if sample_names.valid_new_sample_name(sample.name, self.deposition_number):
                 error_message += _("  Or, the new name must be or begin with the deposition number.")
             self.add_error("new_name", ValidationError(error_message, params=params, code="invalid"))
     return cleaned_data
Example #17
0
def is_referentially_valid(my_layer_forms):
    """Test whether no nickname occurs twice.

    :return:
      whether all nicknames are unique

    :rtype: bool
    """
    referentially_valid = True
    nicknames = set()
    for my_layer_form in my_layer_forms:
        if my_layer_form.is_valid():
            nickname = my_layer_form.cleaned_data["nickname"]
            if nickname in nicknames:
                my_layer_form.add_error(
                    None,
                    ValidationError(_("Nickname is already given."),
                                    code="duplicate"))
                referentially_valid = False
            else:
                nicknames.add(nickname)
    return referentially_valid
Example #18
0
    def clean(self, value):

        if not value and not self.required:
            return None

        # RFC 7159
        if value == 'true':
            return True
        if value == 'false':
            return False
        try:
            return int(value)
        except (TypeError, ValueError):
            pass
        try:
            return float(value)
        except (TypeError, ValueError):
            pass

        # Trap cleaning errors & bubble them up as JSON errors
        try:
            return super(JSONFormFieldBase, self).clean(value)
        except TypeError:
            raise ValidationError(_("Enter valid JSON"))
Example #19
0
    def validate_unique(self):
        """
        Validates the uniqueness of fields, but also handles the localized_fields.
        """
        form_errors = []
        try:
            super(LocalisedForm, self).validate_unique()
        except ValidationError as e:
            form_errors += e.messages

        # add unique validation for the localized fields.
        localized_fields_checks = self._get_localized_field_checks()
        bad_fields = set()

        field_errors, global_errors = self._perform_unique_localized_field_checks(localized_fields_checks)
        bad_fields.union(field_errors)
        form_errors.extend(global_errors)
        
        for field_name in bad_fields:
            del self.cleaned_data[field_name]
        if form_errors:
            # Raise the unique together errors since they are considered
            # form-wide.
            raise ValidationError(form_errors)
Example #20
0
    def _value_from_unjsonfied(self, data):
        gtype = self._clean_graph_type(data)
        if gtype is None:
            return None

        constraint = self.constraint_registry.get_constraint_by_rgraph_type(
            model=self.model,
            rgraph_type=gtype,
        )
        if constraint is None:
            raise ValidationError(
                self.error_messages['graphtypenotallowed'],
                code='graphtypenotallowed',
            )

        cell = self._clean_cell(data, constraint=constraint)
        if not cell:
            return None

        return AbscissaInfo(
            cell=cell,
            graph_type=gtype,
            parameter=self._clean_parameter(data, graph_type=gtype),
        )
Example #21
0
 def clean_number_of_pieces(self):
     if self.cleaned_data["number_of_pieces"] <= 0:
         raise ValidationError(_("Must be at least 1."), code="invalid")
     return self.cleaned_data["number_of_pieces"]
Example #22
0
def is_referentially_valid(original_data_forms, new_name_form_lists, deposition):
    """Test whether all forms are consistent with each other and with the
    database.  For example, no sample name must occur twice, and the sample
    names must not exist within the database already.

    :param original_data_forms: all old samples and pieces numbers
    :param new_name_form_lists: new names for all pieces
    :param deposition: the deposition after which the split takes place

    :type original_data_forms: list of `OriginalDataForm`
    :type new_name_form_lists: list of `NewNameForm`
    :type deposition: `samples.models.Deposition`

    :return:
      whether all forms are consistent with each other and the database

    :rtype: bool
    """
    referentially_valid = True
    samples = list(deposition.samples.all())
    more_than_one_piece = len(original_data_forms) > 1
    new_names = set()
    original_samples = set()
    for original_data_form in original_data_forms:
        if original_data_form.is_valid():
            original_sample = original_data_form.cleaned_data["sample"]
            if original_sample in original_samples:
                original_data_form.add_error("sample", ValidationError(
                    _("Sample %(sample)s occurs multiple times."), params={"sample": original_sample}, code="invalid"))
                referentially_valid = False
            original_samples.add(original_sample)
            if original_sample not in samples:
                original_data_form.add_error("sample", ValidationError(
                    _("Sample %(sample)s doesn't belong to this deposition."), params={"sample": original_sample},
                    code="invalid"))
                referentially_valid = False
            new_name = original_data_form.cleaned_data["new_name"]
            if new_name in new_names:
                original_data_form.add_error("new_name", ValidationError(
                    _("This sample name has been used already on this page."), code="invalid"))
                referentially_valid = False
            new_names.add(new_name)
            if more_than_one_piece and new_name == deposition.number:
                original_data_form.add_error("new_name", ValidationError(
                    _("Since there is more than one piece, the new name must not be exactly the deposition's name."),
                    code="invalid"))
                referentially_valid = False
    if all(original_data_form.is_valid() for original_data_form in original_data_forms):
        assert len(original_samples) <= len(samples)
        if len(original_samples) < len(samples):
            original_data_form.add_error(None, ValidationError(
                _("At least one sample of the original deposition is missing."), code="required"))
            referentially_valid = False
    for new_name_forms, original_data_form in zip(new_name_form_lists, original_data_forms):
        if original_data_form.is_valid():
            original_sample = original_data_form.cleaned_data["sample"]
            if deposition != original_sample.processes.exclude(content_type=ContentType.objects.
                                                               get_for_model(models.Result)) \
                .order_by("-timestamp")[0].actual_instance and original_data_form.cleaned_data["number_of_pieces"] > 1:
                original_data_form.add_error("sample", ValidationError(
                    _("The sample can't be split, because the deposition is not the latest process."), code="invalid"))
                referentially_valid = False
            else:
                for new_name_form in new_name_forms:
                    if new_name_form.is_valid():
                        new_name = new_name_form.cleaned_data["new_name"]
                        if original_data_form.cleaned_data["number_of_pieces"] == 1:
                            if new_name != original_data_form.cleaned_data["new_name"]:
                                new_name_form.add_error("new_name", ValidationError(
                                    _("If you don't split, you can't rename the single piece."), code="invalid"))
                                referentially_valid = False
                        else:
                            if new_name in new_names:
                                new_name_form.add_error("new_name", ValidationError(
                                    _("This sample name has been used already on this page."), code="invalid"))
                                referentially_valid = False
                            new_names.add(new_name)
                            if not new_name.startswith(original_data_form.cleaned_data["new_name"]):
                                new_name_form.add_error("new_name", ValidationError(
                                    _("If you choose a deposition-style name, it must begin with the parent's new name."),
                                    code="invalid"))
                                referentially_valid = False
                            if sample_names.does_sample_exist(new_name):
                                new_name_form.add_error("new_name", ValidationError(_("This sample name exists already."),
                                                                                    code="duplicate"))
                                referentially_valid = False
    return referentially_valid
Example #23
0
 def clean_new_name(self):
     new_name = self.cleaned_data["new_name"]
     sample_name_format = sample_names.sample_name_format(new_name)
     if not sample_name_format:
         raise ValidationError(_("The sample name has an invalid format."), code="invalid")
     return new_name
Example #24
0
    def validate(self, value):
        # super(BillingDiscountField, self).validate(value)
        super().validate(value)

        if not (0 <= value <= 100):
            raise ValidationError(_(u'Enter a number between 0 and 100 (it is a percentage).'))
Example #25
0
 def clean_cpf(self):
     if self.cleaned_data["cpf"].strip() == '':
         raise ValidationError("This field is required.")
     return self.cleaned_data["cpf"]
Example #26
0
 def clean_image(self):
     size_image = self.cleaned_data['image'].size
     if size_image > 2 * 1024 * 1024:  # 2MiB
         raise ValidationError(self.error_messages['image_exceed'])
     return self.cleaned_data['image']
Example #27
0
    def clean(self):
        if self.instance.unsubscribed:
            raise ValidationError(
                _("This subscription has already been unsubscribed from."))

        return super(UnsubscribeRequestForm, self).clean()
Example #28
0
 def clean_telephone(self):
     if self.cleaned_data["telephone"].strip() == '':
         raise ValidationError("This field is required.")
     return self.cleaned_data["telephone"]
Example #29
0
    def clean(self):
        if not self.instance.subscribed:
            raise ValidationError(
                _("This subscription has not yet been activated."))

        return super(UpdateRequestForm, self).clean()
Example #30
0
 def clean_last_name(self):
     if self.cleaned_data["last_name"].strip() == '':
         raise ValidationError("This field is required.")
     return self.cleaned_data["last_name"]