Exemplo n.º 1
0
 def load_json(self):
     try:
         return json.loads(self.entry_json or "{}")
     except:
         raise ValidationError(u"Invalid Json")
Exemplo n.º 2
0
def future_date_validator(date: datetime.date) -> None:
    """Raise ValidationError if the date isn't a future date."""
    if date < datetime.datetime.now(datetime.timezone.utc):
        raise ValidationError("Date must be a future date")
Exemplo n.º 3
0
 def clean(self):
     if not re.match("^[a-zA-Z0-9._-]*$", self.short_name):
         raise ValidationError(_('Please do not use spaces or special characters in the short name '
                                 'field. Only allowed special characters are period (.), hyphen (-) '
                                 'and underscore (_).'))
Exemplo n.º 4
0
 def validate(self, last_pw_change):
     """Password validation with temp."""
     if last_pw_change is not None and last_pw_change.is_temporary:
         raise ValidationError(self.text, code='password-temporary')
Exemplo n.º 5
0
 def save(self, *args, **kwargs):
     if ProjectConfiguration.objects.exists() and not self.pk:
         raise ValidationError('Only one ProjectConfiguration allowed')
     return super(ProjectConfiguration, self).save(*args, **kwargs)
Exemplo n.º 6
0
def validate_users_mail(value):
    if '@' in value:
        return value
    else:
        raise ValidationError('Please provide a valid email')
Exemplo n.º 7
0
def validate_file_extension(value):
    if (not value.name.endswith('.svg')) and (not value.name.endswith('.zip')):
        raise ValidationError(u'Invalid File Type!')
 def clean_old_password(self):
     old_password = self.cleaned_data.get('old_password')
     user = self.instance
     if not user.check_password(old_password):
         raise ValidationError('Invailid password', code='Invalid password')
     return old_password
 def clean_github_profile(self):
     github_profile = self.cleaned_data.get('github_profile')
     if not github_profile.startswith('http://github.com/') and github_profile is not '':
         raise ValidationError('profile address is incorrect', code='wrong address')
     return github_profile
Exemplo n.º 10
0
def only_int(value):
    if value.isdigit() == False:
        raise ValidationError('ID contains characters')
Exemplo n.º 11
0
Arquivo: models.py Projeto: lukkol/vmc
 def save(self,  force_insert=False, force_update=False, using=None,
          update_fields=None):
     if not self.pk and TheHive4.objects.exists():
         raise ValidationError('There can be only one TheHive4 configuration')
     return super().save(force_insert=force_insert, force_update=force_update, using=using,
                         update_fields=update_fields)
Exemplo n.º 12
0
 def clean_email(self):
     email = self.cleaned_data['email']
     if "ericsson.com" not in email:
         raise ValidationError(('Not an ericsson email'))
     return email
Exemplo n.º 13
0
def validate_number(value):
    value = str(value)

    if(len(value) != 10):
        raise ValidationError("Please enter valid Phone Number")
Exemplo n.º 14
0
def validate_skills(value):
    if(len(value) > 5):
        raise ValidationError("Please enter a max of 5 skills only")
Exemplo n.º 15
0
 def clean_password(self):
     password = self.cleaned_data.get('password')
     if not self.user.check_password(password):
         raise ValidationError(_('Invalid password'))
     return password
Exemplo n.º 16
0
 def clean_slug(self):
     new_slug = self.cleaned_data['slug'].lower()
     if new_slug == 'create':
         raise ValidationError('Slug may not create')
     return new_slug
Exemplo n.º 17
0
def validate_content(value):
    content = value
    if content == "":
        raise ValidationError("Cannot be blank")
    return value
Exemplo n.º 18
0
 def validate(self, value):
     if value in validators.EMPTY_VALUES and self.required:
         raise ValidationError(self.error_messages['required'])
Exemplo n.º 19
0
 def clean(self):
     self.title = self.title.strip()
     self.body = self.body.strip()
     if not self.user and not (self.name and self.email):
         raise ValidationError(
             _("Anonymous reviews must include a name and an email"))
Exemplo n.º 20
0
class Field(object):
    widget = TextInput # Default widget to use when rendering this type of Field.
    hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
    default_validators = [] # Default set of validators
    default_error_messages = {
        'required': _(u'This field is required.'),
        'invalid': _(u'Enter a valid value.'),
    }

    # Tracks each time a Field instance is created. Used to retain order.
    creation_counter = 0

    def __init__(self, required=True, widget=None, label=None, initial=None,
                 help_text=None, error_messages=None, show_hidden_initial=False,
                 validators=[], localize=False):
        # required -- Boolean that specifies whether the field is required.
        #             True by default.
        # widget -- A Widget class, or instance of a Widget class, that should
        #           be used for this Field when displaying it. Each Field has a
        #           default Widget that it'll use if you don't specify this. In
        #           most cases, the default widget is TextInput.
        # label -- A verbose name for this field, for use in displaying this
        #          field in a form. By default, Django will use a "pretty"
        #          version of the form field name, if the Field is part of a
        #          Form.
        # initial -- A value to use in this Field's initial display. This value
        #            is *not* used as a fallback if data isn't given.
        # help_text -- An optional string to use as "help text" for this Field.
        # error_messages -- An optional dictionary to override the default
        #                   messages that the field will raise.
        # show_hidden_initial -- Boolean that specifies if it is needed to render a
        #                        hidden widget with initial value after widget.
        # validators -- List of addtional validators to use
        # localize -- Boolean that specifies if the field should be localized.
        if label is not None:
            label = smart_unicode(label)
        self.required, self.label, self.initial = required, label, initial
        self.show_hidden_initial = show_hidden_initial
        if help_text is None:
            self.help_text = u''
        else:
            self.help_text = smart_unicode(help_text)
        widget = widget or self.widget
        if isinstance(widget, type):
            widget = widget()

        # Trigger the localization machinery if needed.
        self.localize = localize
        if self.localize:
            widget.is_localized = True

        # Let the widget know whether it should display as required.
        widget.is_required = self.required

        # Hook into self.widget_attrs() for any Field-specific HTML attributes.
        extra_attrs = self.widget_attrs(widget)
        if extra_attrs:
            widget.attrs.update(extra_attrs)

        self.widget = widget

        # Increase the creation counter, and save our local copy.
        self.creation_counter = Field.creation_counter
        Field.creation_counter += 1

        messages = {}
        for c in reversed(self.__class__.__mro__):
            messages.update(getattr(c, 'default_error_messages', {}))
        messages.update(error_messages or {})
        self.error_messages = messages

        self.validators = self.default_validators + validators

    def prepare_value(self, value):
        return value

    def to_python(self, value):
        return value

    def validate(self, value):
        if value in validators.EMPTY_VALUES and self.required:
            raise ValidationError(self.error_messages['required'])

    def run_validators(self, value):
        if value in validators.EMPTY_VALUES:
            return
        errors = []
        for v in self.validators:
            try:
                v(value)
            except ValidationError, e:
                if hasattr(e, 'code') and e.code in self.error_messages:
                    message = self.error_messages[e.code]
                    if e.params:
                        message = message % e.params
                    errors.append(message)
                else:
                    errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)
Exemplo n.º 21
0
 def fail(message):
     if raise_exception:
         raise ValidationError(message)
     else:
         self.error = message
         return False
Exemplo n.º 22
0
 def to_python(self, value):
     if not value:
         return []
     elif not isinstance(value, (list, tuple)):
         raise ValidationError(self.error_messages['invalid_list'])
     return [smart_unicode(val) for val in value]
Exemplo n.º 23
0
    def get_orderability_errors(  # noqa (C901)
            self, supplier, quantity, customer, ignore_minimum=False):
        """
        Yield ValidationErrors that would cause this product to not be orderable.

        :param supplier: Supplier to order this product from. May be None.
        :type supplier: shuup.core.models.Supplier
        :param quantity: Quantity to order.
        :type quantity: int|Decimal
        :param customer: Customer contact.
        :type customer: shuup.core.models.Contact
        :param ignore_minimum: Ignore any limitations caused by quantity minimums.
        :type ignore_minimum: bool
        :return: Iterable[ValidationError]
        """
        for error in self.get_visibility_errors(customer):
            yield error

        if supplier is None and not self.suppliers.exists():
            # `ShopProduct` must have at least one `Supplier`.
            # If supplier is not given and the `ShopProduct` itself
            # doesn't have suppliers we cannot sell this product.
            yield ValidationError(
                _('The product has no supplier.'),
                code="no_supplier"
            )

        if not ignore_minimum and quantity < self.minimum_purchase_quantity:
            yield ValidationError(
                _('The purchase quantity needs to be at least %d for this product.') % self.minimum_purchase_quantity,
                code="purchase_quantity_not_met"
            )

        if supplier and not self.suppliers.filter(pk=supplier.pk).exists():
            yield ValidationError(
                _('The product is not supplied by %s.') % supplier,
                code="invalid_supplier"
            )

        if self.product.is_package_parent():
            for child_product, child_quantity in six.iteritems(self.product.get_package_child_to_quantity_map()):
                child_shop_product = child_product.get_shop_instance(shop=self.shop)
                if not child_shop_product:
                    yield ValidationError("%s: Not available in %s" % (child_product, self.shop), code="invalid_shop")
                for error in child_shop_product.get_orderability_errors(
                        supplier=supplier,
                        quantity=(quantity * child_quantity),
                        customer=customer,
                        ignore_minimum=ignore_minimum
                ):
                    code = getattr(error, "code", None)
                    yield ValidationError("%s: %s" % (child_product, error), code=code)

        if supplier and self.product.stock_behavior == StockBehavior.STOCKED:
            for error in supplier.get_orderability_errors(self, quantity, customer=customer):
                yield error

        purchase_multiple = self.purchase_multiple
        if quantity > 0 and purchase_multiple > 1 and (quantity % purchase_multiple) != 0:
            p = (quantity // purchase_multiple)
            smaller_p = max(purchase_multiple, p * purchase_multiple)
            larger_p = max(purchase_multiple, (p + 1) * purchase_multiple)
            if larger_p == smaller_p:
                message = _('The product can only be ordered in multiples of %(package_size)s, '
                            'for example %(smaller_p)s %(unit)s.') % {
                    "package_size": purchase_multiple,
                    "smaller_p": smaller_p,
                    "unit": self.product.sales_unit,
                }
            else:
                message = _('The product can only be ordered in multiples of %(package_size)s, '
                            'for example %(smaller_p)s or %(larger_p)s %(unit)s.') % {
                    "package_size": purchase_multiple,
                    "smaller_p": smaller_p,
                    "larger_p": larger_p,
                    "unit": self.product.sales_unit,
                }
            yield ValidationError(message, code="invalid_purchase_multiple")

        for receiver, response in get_orderability_errors.send(
            ShopProduct, shop_product=self, customer=customer, supplier=supplier, quantity=quantity
        ):
            for error in response:
                yield error
Exemplo n.º 24
0
class MultiValueField(Field):
    """
    A Field that aggregates the logic of multiple Fields.

    Its clean() method takes a "decompressed" list of values, which are then
    cleaned into a single value according to self.fields. Each value in
    this list is cleaned by the corresponding field -- the first value is
    cleaned by the first field, the second value is cleaned by the second
    field, etc. Once all fields are cleaned, the list of clean values is
    "compressed" into a single value.

    Subclasses should not have to implement clean(). Instead, they must
    implement compress(), which takes a list of valid values and returns a
    "compressed" version of those values -- a single value.

    You'll probably want to use this with MultiWidget.
    """
    default_error_messages = {
        'invalid': _(u'Enter a list of values.'),
    }

    def __init__(self, fields=(), *args, **kwargs):
        super(MultiValueField, self).__init__(*args, **kwargs)
        # Set 'required' to False on the individual fields, because the
        # required validation will be handled by MultiValueField, not by those
        # individual fields.
        for f in fields:
            f.required = False
        self.fields = fields

    def validate(self, value):
        pass

    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages['invalid'])
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if self.required and field_value in validators.EMPTY_VALUES:
                raise ValidationError(self.error_messages['required'])
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError, e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        return out
Exemplo n.º 25
0
def validate_even(value):
    if value % 2 != 0:
        raise ValidationError(
            _('%(value)s is not an even number'),
            params={'value': value},
        )
Exemplo n.º 26
0
def validate_token(value):
    if not re.match('[0-9]+:[-_a-zA-Z0-9]+', value):
        raise ValidationError(_("%(value)s is not a valid token"), params={'value': value})
Exemplo n.º 27
0
 def validate(self, resource):
     if resource.state not in (
         models.Resource.States.OK,
         models.Resource.States.ERRED,
     ):
         raise ValidationError(_('Resource has to be in OK or ERRED state.'))
Exemplo n.º 28
0
 def find_col(col_title):
     for idx, cell in enumerate(heading_row):
         if col_title.matches(cell.value):
             return idx
     raise ValidationError('Column heading "{}" was not found.'.format(
         col_title))
Exemplo n.º 29
0
 def save(self, *args, **kwargs):
     if self.buy_price <= 1 or self.buy_price >= 100:
         raise ValidationError(f'{self.buy_price} minimum 1 maximal 99')
     super().save(*args, **kwargs)
Exemplo n.º 30
0
 def load_json_params(self):
     if self.source_json_params:
         try:
             return json.loads(self.source_json_params or "{}")
         except:
             raise ValidationError(_(u'Invalid JSON'))