Exemplo n.º 1
0
    def validate(data, schema):
        """
        Validates the data against given schema and checks validity of ds_id and ds_spirit.

        :param data: The data to validate
        :param schema: The JSON schema to use for validation.
        :return: Valid data
        """

        if isinstance(data, dict):
            properties = data
        elif isinstance(data, Individual):
            properties = data.properties
        else:
            raise ValidationError(
                "An Individual can only work with a dict as data and got {} instead".format(type(data))
            )
        if "_id" in properties:
            del properties["_id"]

        try:
            jsonschema.validate(properties, schema)
        except SchemaValidationError as exc:
            django_exception = ValidationError(exc.message)
            django_exception.schema = exc.schema
            raise django_exception
 def 加外語資料(cls, 內容):
     try:
         原本外語 = cls._找外語資料(內容)
         錯誤 = ValidationError('已經有相同的外語資料了')
         錯誤.平臺項目編號 = 原本外語.編號()
         raise 錯誤
     except ObjectDoesNotExist:
         pass
     外語 = 外語表.加資料(cls._補預設欄位(內容, 字詞))
     return cls.objects.create(外語=外語)
Exemplo n.º 3
0
 def validate_unique(self, exclude=None):
     if not self.id:
         try:
             Flowvisor.objects.get(name=self.name)
             e = ValidationError(_("%(model_name)s with this %(field_label)s already exists.") % {"field_label": self._meta.get_field('name').verbose_name, "model_name": self._meta.verbose_name})
             e.message_dict = {}
             e.message_dict["name"] = e.messages
             raise e
         except Flowvisor.DoesNotExist:
             return self.name
     super(Flowvisor, self).validate_unique(exclude)
Exemplo n.º 4
0
 def save(self, image, save=True):
     try:
         super(FieldWallet, self).save(image)
     except IOError:
         # Пока никакой интернационализации, только хардкор.
         e = ValidationError(u"Неверный формат изображения.")
         e.message_dict = { self.field.name: [u"Выберите другой файл."] }
         raise e
     if self.field.process_all_formats:
         self.process_all_formats()
     if save:
         self.instance.save()
Exemplo n.º 5
0
 def clean(self):
     try: 
         self.dataSource = DataSource(self.fgdb_path)
     except:
         raise ValidationError(self.fgdb_path + " could not be opened by GDAL")
     else:
         validator = GdbValidator(self.dataSource)
         valid = validator.isValid()
         if not valid:
             err = ValidationError(validator.validationMessage())
             err.asJson = validator.logs.asJson()
             raise err
Exemplo n.º 6
0
    def add_error(self, field, error):
        """
        Update the content of `self._errors`.

        The `field` argument is the name of the field to which the errors
        should be added. If its value is None the errors will be treated as
        NON_FIELD_ERRORS.

        The `error` argument can be a single error, a list of errors, or a
        dictionary that maps field names to lists of errors. What we define as
        an "error" can be either a simple string or an instance of
        ValidationError with its message attribute set and what we define as
        list or dictionary can be an actual `list` or `dict` or an instance
        of ValidationError with its `error_list` or `error_dict` attribute set.

        If `error` is a dictionary, the `field` argument *must* be None and
        errors will be added to the fields that correspond to the keys of the
        dictionary.
        """
        if not isinstance(error, ValidationError):
            # Normalize to ValidationError and let its constructor
            # do the hard work of making sense of the input.
            error = ValidationError(error)

        if hasattr(error, 'error_dict'):
            if field is not None:
                raise TypeError(
                    "The argument `field` must be `None` when the `error` "
                    "argument contains errors for multiple fields."
                )
            else:
                error = error.error_dict
        else:
            error = {field or NON_FIELD_ERRORS: error.error_list}

        for field, error_list in error.items():
            if field not in self.errors:
                if field != NON_FIELD_ERRORS and field not in self.fields:
                    raise ValueError(
                        "'%s' has no field named '%s'." % (self.__class__.__name__, field))
                if field == NON_FIELD_ERRORS:
                    self._errors[field] = self.error_class(error_class='nonfield')
                else:
                    self._errors[field] = self.error_class()
            self._errors[field].extend(error_list)
            if field in self.cleaned_data:
                del self.cleaned_data[field]
Exemplo n.º 7
0
    def add_error(self, field, error):
        """
        Standard django form does not support more structured errors
        (for example error dict that contains another error dict).
        For this purpose pyston creates RESTError class and we must rewrite this method to allow these
        complex error messages.
        """
        if isinstance(error, RESTError):
            if not field:
                raise ValueError('Field must be set for RESTError')
            self._errors[field] = error
        else:
            if not isinstance(error, ValidationError):
                # Normalize to ValidationError and let its constructor
                # do the hard work of making sense of the input.
                error = ValidationError(error)

            if hasattr(error, 'error_dict'):
                if field is not None:
                    raise TypeError(
                        "The argument `field` must be `None` when the `error` "
                        "argument contains errors for multiple fields."
                    )
                else:
                    error = error.error_dict
            else:
                error = {field or NON_FIELD_ERRORS: error.error_list}

            for field, error_list in error.items():
                if field not in self.errors:
                    if field == NON_FIELD_ERRORS:
                        self._errors[field] = self.error_class(error_class='nonfield')
                    else:
                        self._errors[field] = self.error_class()
                self._errors[field].extend(error_list)
                if field in self.cleaned_data:
                    del self.cleaned_data[field]
Exemplo n.º 8
0
 def setUp(self):
     # Create a ValidationEror with a mix of field-specific and non-field-specific errors
     self.non_field_errors = ValidationError(['Error 1', 'Error 2', 'Error 3'])
     self.field_errors = ValidationError({
         'name': ['Error 4', 'Error 5'],
         'birthday': ['Error 6', 'Error 7'],
     })
     combined_error_dict = self.non_field_errors.update_error_dict(
         self.field_errors.error_dict.copy()
     )
     e = ValidationError(combined_error_dict)
     # Create an InvalidRow instance to use in tests
     self.obj = InvalidRow(
         number=1,
         validation_error=e,
         values={'name': 'ABC', 'birthday': '123'}
     )
Exemplo n.º 9
0
class InvalidRowTest(TestCase):

    def setUp(self):
        # Create a ValidationEror with a mix of field-specific and non-field-specific errors
        self.non_field_errors = ValidationError(['Error 1', 'Error 2', 'Error 3'])
        self.field_errors = ValidationError({
            'name': ['Error 4', 'Error 5'],
            'birthday': ['Error 6', 'Error 7'],
        })
        combined_error_dict = self.non_field_errors.update_error_dict(
            self.field_errors.error_dict.copy()
        )
        e = ValidationError(combined_error_dict)
        # Create an InvalidRow instance to use in tests
        self.obj = InvalidRow(
            number=1,
            validation_error=e,
            values={'name': 'ABC', 'birthday': '123'}
        )

    def test_error_count(self):
        self.assertEqual(self.obj.error_count, 7)

    def test_non_field_specific_errors(self):
        result = self.obj.non_field_specific_errors
        self.assertIsInstance(result, list)
        self.assertEqual(result, ['Error 1', 'Error 2', 'Error 3'])

    def test_field_specific_errors(self):
        result = self.obj.field_specific_errors
        self.assertIsInstance(result, dict)
        self.assertEqual(len(result), 2)
        self.assertEqual(result['name'], ['Error 4', 'Error 5'])
        self.assertEqual(result['birthday'], ['Error 6', 'Error 7'])

    def test_creates_error_dict_from_error_list_if_validation_error_only_has_error_list(self):
        obj = InvalidRow(
            number=1,
            validation_error=self.non_field_errors,
            values={}
        )
        self.assertIsInstance(obj.error_dict, dict)
        self.assertIn(NON_FIELD_ERRORS, obj.error_dict)
        self.assertEqual(obj.error_dict[NON_FIELD_ERRORS], ['Error 1', 'Error 2', 'Error 3'])
Exemplo n.º 10
0
def TermsOfUse(value):
    if not value:
        raise ValidationError('Please check the box to proceed')
Exemplo n.º 11
0
def _pages_from_json(request, offering, data):
    with django.db.transaction.atomic():
        try:
            data = data.decode('utf-8-sig')
        except UnicodeDecodeError:
            raise ValidationError("Bad UTF-8 data in file.")
            
        try:
            data = json.loads(data)
        except ValueError as e:
            raise ValidationError('JSON decoding error.  Exception was: "' + str(e) + '"')
        
        if not isinstance(data, dict):
            raise ValidationError('Outer JSON data structure must be an object.')
        if 'userid' not in data or 'token' not in data:
            raise ValidationError('Outer JSON data object must contain keys "userid" and "token".')
        if 'pages' not in data:
            raise ValidationError('Outer JSON data object must contain keys "pages".')
        if not isinstance(data['pages'], list):
            raise ValidationError('Value for "pages" must be a list.')
        
        try:
            user = Person.objects.get(userid=data['userid'])
            member = Member.objects.exclude(role='DROP').get(person=user, offering=offering)
        except (Person.DoesNotExist, Member.DoesNotExist):
            raise ValidationError('Person with that userid does not exist.')
        
        if 'pages-token' not in user.config or user.config['pages-token'] != data['token']:
            e = ValidationError('Could not validate authentication token.')
            e.status = 403
            raise e
        
        # if we get this far, the user is authenticated and we can start processing the pages...
        
        for i, pdata in enumerate(data['pages']):
            if not isinstance(pdata, dict):
                raise ValidationError('Page #%i entry structure must be an object.' % (i))
            if 'label' not in pdata:
                raise ValidationError('Page #%i entry does not have a "label".' % (i))
            
            # handle changes to the Page object
            pages = Page.objects.filter(offering=offering, label=pdata['label'])
            if pages:
                page = pages[0]
                old_ver = page.current_version()
            else:
                page = Page(offering=offering, label=pdata['label'])
                old_ver = None

            # check write permissions
            
            # mock the request object enough to satisfy _check_allowed()
            class FakeRequest(object):
                is_authenticated = True
            fake_request = FakeRequest()
            fake_request.user = FakeRequest()
            fake_request.user.username = user.userid

            if old_ver:
                m = _check_allowed(fake_request, offering, page.can_write, page.editdate())
            else:
                m = _check_allowed(fake_request, offering, offering.page_creators())
            if not m:
                raise ValidationError('You can\'t edit page #%i.' % (i))
            
            # handle Page attributes
            if 'can_read' in pdata:
                if type(pdata['can_read']) != str or pdata['can_read'] not in ACL_DESC:
                    raise ValidationError('Page #%i "can_read" value must be one of %s.'
                                          % (i, ','.join(list(ACL_DESC.keys()))))
                
                page.can_read = pdata['can_read']

            if 'can_write' in pdata:
                if type(pdata['can_write']) != str or pdata['can_write'] not in WRITE_ACL_DESC:
                    raise ValidationError('Page #%i "can_write" value must be one of %s.'
                                          % (i, ','.join(list(WRITE_ACL_DESC.keys()))))
                if m.role == 'STUD':
                    raise ValidationError('Page #%i: students can\'t change can_write value.' % (i))
                page.can_write = pdata['can_write']
            
            if 'new_label' in pdata:
                if type(pdata['new_label']) != str:
                    raise ValidationError('Page #%i "new_label" value must be a string.' % (i))
                if m.role == 'STUD':
                    raise ValidationError('Page #%i: students can\'t change label value.' % (i))
                if Page.objects.filter(offering=offering, label=pdata['new_label']):
                    raise ValidationError('Page #%i: there is already a page with that "new_label".' % (i))

                page.label = pdata['new_label']

            page.save()

            # handle PageVersion changes
            ver = PageVersion(page=page, editor=member)
            
            if 'title' in pdata:
                if type(pdata['title']) != str:
                    raise ValidationError('Page #%i "title" value must be a string.' % (i))
                
                ver.title = pdata['title']
            elif old_ver:
                ver.title = old_ver.title
            else:
                raise ValidationError('Page #%i has no "title" for new page.' % (i))

            if 'comment' in pdata:
                if type(pdata['comment']) != str:
                    raise ValidationError('Page #%i "comment" value must be a string.' % (i))
                
                ver.comment = pdata['comment']

            if 'use_math' in pdata:
                if type(pdata['use_math']) != bool:
                    raise ValidationError('Page #%i "comment" value must be a boolean.' % (i))

                ver.set_math(pdata['use_math'])

            if 'markup' in pdata:
                if isinstance(pdata['markup'], str):
                    raise ValidationError('Page #%i "markup" value must be a string.' % (i))

                ver.set_markup(pdata['markup'])

            if 'wikitext-base64' in pdata:
                if type(pdata['wikitext-base64']) != str:
                    raise ValidationError('Page #%i "wikitext-base64" value must be a string.' % (i))
                try:
                    wikitext = base64.b64decode(pdata['wikitext-base64']).decode('utf8')
                except TypeError:
                    raise ValidationError('Page #%i "wikitext-base64" contains bad base BASE64 data.' % (i))
                
                ver.wikitext = wikitext
            elif 'wikitext' in pdata:
                if type(pdata['wikitext']) != str:
                    raise ValidationError('Page #%i "wikitext" value must be a string.' % (i))
                
                ver.wikitext = pdata['wikitext']
            elif old_ver:
                ver.wikitext = old_ver.wikitext
            else:
                raise ValidationError('Page #%i has no wikitext for new page.' % (i))

            ver.save()
        
        return user
Exemplo n.º 12
0
def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]
    valid_extensions = ['.pdf', '.doc', '.docx']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension.')
Exemplo n.º 13
0
def task_document_extension(value):
    ext = os.path.splitext(value.name)[1]

    if not ext.lower() in TASK_ALLOWED_EXTS:
        raise ValidationError(
            f'not allowed ext, allowed ({TASK_ALLOWED_EXTS})')
Exemplo n.º 14
0
 def clean(self):
     if ' ' in self.code:
         raise ValidationError(_('Account code must not contain spaces'))
Exemplo n.º 15
0
 def __init__(self, field_name, message):
     self.field_name = field_name
     print('Field error', self.field_name, message) 
     _ValidationError.__init__(self, message)
Exemplo n.º 16
0
    def clean(self):
        d = super().clean()
        if not d['all_events'] and not d['limit_events']:
            raise ValidationError(_('Your device will not have access to anything, please select some events.'))

        return d
Exemplo n.º 17
0
 def clean_file(self):
     file = self.cleaned_data.get("file")
     if file and not isinstance(file, Image):
         raise ValidationError(_("Only images allowed in this field"))
     return file
Exemplo n.º 18
0
 def clean_backorder_maximum(self):
     backorder_maximum = self.cleaned_data.get("backorder_maximum")
     if backorder_maximum is not None and backorder_maximum < 0:
         raise ValidationError(
             _("Backorder maximum must be greater than or equal to 0."))
     return backorder_maximum
Exemplo n.º 19
0
 def clean_slug(self):
     new_slug = self.cleaned_data['slug'].lower()
     if new_slug == 'create':
         raise ValidationError('Slug may not be "Create"')
     return new_slug
Exemplo n.º 20
0
def validate_postal_code(value):
    if len(str(value)) != 10:
        raise ValidationError(
            'not a 10 digit postal code',
            params = {'value': value}
        )
Exemplo n.º 21
0
 def clean(self):
     super().clean()
     if self.status == self.STATUS.rejected and not self.rejection_reason:
         msg = _('Must give a reason to reject a comment')
         raise ValidationError({'rejection_reason': msg})
Exemplo n.º 22
0
def app_validate(value):
    app = re.match('.*(apk|exe|mar|ipa|dmg|rpm|deb)$', value.name)
    if not app:
        raise ValidationError('客户端类型错误')
Exemplo n.º 23
0
 def clean(self):
     from django.core.exceptions import ValidationError
     if (not self.text_value) and (not self.int_value) and (not self.float_value):
         raise ValidationError("There must be at least one non-empty value!")
Exemplo n.º 24
0
 def confirm_login_allowed(self, user):
     if not user.is_active:
         raise ValidationError(
             "This account is inactive.",
             code='inactive',
         )
Exemplo n.º 25
0
 def __init__(self, document):
     if not document.name.endswith('.pdf'):
         raise ValidationError("Only PDF file is accepted")
Exemplo n.º 26
0
 def as_data(self):
     return ValidationError(self.data).error_list
Exemplo n.º 27
0
    def receive_line_item(self,
                          line,
                          location,
                          quantity,
                          user,
                          status=StockStatus.OK,
                          **kwargs):
        """
        Receive a line item (or partial line item) against this PurchaseOrder
        """

        # Extract optional batch code for the new stock item
        batch_code = kwargs.get('batch_code', '')

        # Extract optional list of serial numbers
        serials = kwargs.get('serials', None)

        # Extract optional notes field
        notes = kwargs.get('notes', '')

        # Extract optional barcode field
        barcode = kwargs.get('barcode', None)

        # Prevent null values for barcode
        if barcode is None:
            barcode = ''

        if self.status != PurchaseOrderStatus.PLACED:
            raise ValidationError(
                "Lines can only be received against an order marked as 'PLACED'"
            )

        try:
            if quantity < 0:
                raise ValidationError(
                    {"quantity": _("Quantity must be a positive number")})
            quantity = InvenTree.helpers.clean_decimal(quantity)
        except TypeError:
            raise ValidationError({"quantity": _("Invalid quantity provided")})

        # Create a new stock item
        if line.part and quantity > 0:

            # Determine if we should individually serialize the items, or not
            if type(serials) is list and len(serials) > 0:
                serialize = True
            else:
                serialize = False
                serials = [None]

            for sn in serials:

                stock = stock_models.StockItem(
                    part=line.part.part,
                    supplier_part=line.part,
                    location=location,
                    quantity=1 if serialize else quantity,
                    purchase_order=self,
                    status=status,
                    batch=batch_code,
                    serial=sn,
                    purchase_price=line.purchase_price,
                    uid=barcode)

                stock.save(add_note=False)

                tracking_info = {
                    'status': status,
                    'purchaseorder': self.pk,
                }

                stock.add_tracking_entry(
                    StockHistoryCode.RECEIVED_AGAINST_PURCHASE_ORDER,
                    user,
                    notes=notes,
                    deltas=tracking_info,
                    location=location,
                    purchaseorder=self,
                    quantity=quantity)

        # Update the number of parts received against the particular line item
        line.received += quantity
        line.save()

        # Has this order been completed?
        if len(self.pending_line_items()) == 0:

            self.received_by = user
            self.complete_order()  # This will save the model
Exemplo n.º 28
0
def task_document_size(value):

    if value.size > 200000:
        raise ValidationError('invalid file size')
Exemplo n.º 29
0
def validate_checksumed_address(address):
    if not Web3.isChecksumAddress(address):
        raise ValidationError(
            '%(address)s has an invalid checksum',
            params={'address': address},
        )
Exemplo n.º 30
0
def validate_template_path(name):
    try:
        engine.get_template(name)
    except TemplateDoesNotExist:
        raise ValidationError(_('Template not found.'))
Exemplo n.º 31
0
 def clean_resume(self):
     """Tests if the resume is in a PDF file."""
     resume = self.cleaned_data['resume']
     if resume.content_type != 'application/pdf':
         raise ValidationError("File is not a PDF.")
     return resume
Exemplo n.º 32
0
def PhoneValidator(value):
    if type(value) is not int \
     or not ( len(str(value)) == 9 or (len(str(value)) == 12 and str(value).startswith('212')) ):
        raise ValidationError('This phone number is invalid.')
Exemplo n.º 33
0
 def clean(self):
     if self.transition not in self.workflow_instance.get_transition_choices(_user=self.user):
         raise ValidationError(_('Not a valid transition choice.'))
Exemplo n.º 34
0
 def __init__(self, field_name, message):
     self.field_name = field_name
     _ValidationError.__init__(self, message)
Exemplo n.º 35
0
def validate_ipv6_address(value):
    if not is_valid_ipv6_address(value):
        raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
Exemplo n.º 36
0
 def __init__(self):
   ValidationError.__init__(self,
     _(u"El problema debe tener más de una ciudad."))
Exemplo n.º 37
0
"""
Exemplo n.º 38
0
     
     for name, field in self.api_fields.iteritems():
         
         if not name in obj:
             value = None
         else:
             value = obj[name]
         
         try:
             cleaned_value = field.unserialize(value)
             new_dict[name] = cleaned_value
         except ValidationError, e:
             errors[name] = e.messages
     
     if errors:
         error = ValidationError("There were multiple errors when validating the data.")
         error.messages = errors
         
         raise error
     
     return new_dict
 
 def _content_types_urlconf(self):
     types = "|".join(self.serializer.content_types.keys())
     
     return r"(?P<content_type>(%s))" % (types, )
 
 def _determine_content_type_from_request(self, request, content_type=None):
     request_ct = request.META.get("HTTP_ACCEPT", None)
     
     allowed_formats = self.serializer.content_types.keys()
Exemplo n.º 39
0
def validate_earning(sender, instance: Transaction, **kwargs):
    if instance.transaction_type == Transaction.EARNING_TYPE and instance.amount < 0:
        raise ValidationError(
            {'message': _('Earning amount should be a positive number.')})
Exemplo n.º 40
0
def version_validate(value):
    version = re.match('\d{1,2}\.\d{1,3}\.\d*$', value)
    if not version:
        raise ValidationError('版本号格式错误')
Exemplo n.º 41
0
def validate_version(value):
    """
    Validate version string. Allow empty value for initial state.
    """
    if not re.fullmatch(r'[0-9]+(\.[0-9]+)+', value) or '..' in value:
        raise ValidationError('Version may only contain numbers and dots, and must begin and end with a number.')
Exemplo n.º 42
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.mode == ProductMode.SIMPLE_VARIATION_PARENT:
            sellable = False
            for child_product in self.product.variation_children.all():
                child_shop_product = child_product.get_shop_instance(self.shop)
                if child_shop_product.is_orderable(
                        supplier=supplier,
                        customer=customer,
                        quantity=child_shop_product.minimum_purchase_quantity,
                        allow_cache=False
                ):
                    sellable = True
                    break
            if not sellable:
                yield ValidationError(_("Product has no sellable children"), code="no_sellable_children")
        elif self.product.mode == ProductMode.VARIABLE_VARIATION_PARENT:
            from shuup.core.models import ProductVariationResult
            sellable = False
            for combo in self.product.get_all_available_combinations():
                res = ProductVariationResult.resolve(self.product, combo["variable_to_value"])
                if not res:
                    continue
                child_shop_product = res.get_shop_instance(self.shop)
                if child_shop_product.is_orderable(
                        supplier=supplier,
                        customer=customer,
                        quantity=child_shop_product.minimum_purchase_quantity,
                        allow_cache=False
                ):
                    sellable = True
                    break
            if not sellable:
                yield ValidationError(_("Product has no sellable children"), code="no_sellable_children")

        if self.product.is_package_parent():
            for child_product, child_quantity in six.iteritems(self.product.get_package_child_to_quantity_map()):
                try:
                    child_shop_product = child_product.get_shop_instance(shop=self.shop, allow_cache=False)
                except ShopProduct.DoesNotExist:
                    yield ValidationError("%s: Not available in %s" % (child_product, self.shop), code="invalid_shop")
                else:
                    for error in child_shop_product.get_orderability_errors(
                            supplier=supplier,
                            quantity=(quantity * child_quantity),
                            customer=customer,
                            ignore_minimum=ignore_minimum
                    ):
                        message = getattr(error, "message", "")
                        code = getattr(error, "code", None)
                        yield ValidationError("%s: %s" % (child_product, message), 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.º 43
0
    def modify_item(self,
                    product,
                    relative=None,
                    absolute=None,
                    recalculate=True):
        """
        Updates order with the given product

        - ``relative`` or ``absolute``: Add/subtract or define order item amount exactly
        - ``recalculate``: Recalculate order after cart modification (defaults to ``True``)

        Returns the ``OrderItem`` instance; if quantity is zero, the order item instance
        is deleted, the ``pk`` attribute set to ``None`` but the order item is returned
        anway.
        """

        assert (relative is None) != (
            absolute is None), 'One of relative or absolute must be provided.'

        if self.status >= self.CONFIRMED:
            raise ValidationError(
                _('Cannot modify order once it has been confirmed.'),
                code='order_sealed')

        try:
            item = self.items.get(product=product)
        except self.items.model.DoesNotExist:
            item = self.items.model(
                order=self,
                product=product,
                quantity=0,
                currency=self.currency,
            )

        if relative is not None:
            item.quantity += relative
        else:
            item.quantity = absolute

        if item.quantity > 0:
            try:
                price = product.get_price(currency=self.currency,
                                          orderitem=item)
            except ObjectDoesNotExist:
                logger.error(
                    'No price could be found for %s with currency %s' %
                    (product, self.currency))
                raise

            price.handle_order_item(item)
            product.handle_order_item(item)
            item.save()
        else:
            if item.pk:
                item.delete()
                item.pk = None

        if recalculate:
            self.recalculate_total()

            # Reload item instance from DB to preserve field values
            # changed in recalculate_total
            if item.pk:
                item = self.items.get(pk=item.pk)

        try:
            self.validate(self.VALIDATE_BASE)
        except ValidationError:
            if item.pk:
                item.delete()
            raise

        return item
Exemplo n.º 44
0
 def __init__(self):
   ValidationError.__init__(self,
     _(u"El problema no tiene registrada ninguna ciudad."))
Exemplo n.º 45
0
def validate_year(year):
    current_year = date.today().year
    if year > current_year:
        raise ValidationError(
            f"Год не может превышать {current_year}"
        )
Exemplo n.º 46
0
def validate_oldfilename(value):
    """
    Check if string is potentially a file base name.
    """
    if '/' in value or value == '' or value == '.' or value == '..':
        raise ValidationError('Not a valid file base name.')
Exemplo n.º 47
0
 def clean(self):
     #ToDo: non comments, how to make it better? Overload Validation Error?
     if not (self.parent or self.title):
         error = ValidationError("")
         error.message_dict = {u"title": u"Field is required."}
         raise error