当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ValidationError方法代码示例

本文整理汇总了Python中django.core.exceptions.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ValidationError方法的具体用法?Python exceptions.ValidationError怎么用?Python exceptions.ValidationError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.exceptions的用法示例。


在下文中一共展示了exceptions.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate_org_relation

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def _validate_org_relation(self, rel, field_error='organization'):
        """
        if the relation is owned by a specific organization
        this object must be related to the same organization
        """
        # avoid exceptions caused by the relation not being set
        if not hasattr(self, rel):
            return
        rel = getattr(self, rel)
        if (
            rel
            and rel.organization_id
            and str(self.organization_id) != str(rel.organization_id)
        ):
            message = _(
                'Please ensure that the organization of this {object_label} '
                'and the organization of the related {related_object_label} match.'
            )
            message = message.format(
                object_label=self._meta.verbose_name,
                related_object_label=rel._meta.verbose_name,
            )
            raise ValidationError({field_error: message}) 
开发者ID:openwisp,项目名称:openwisp-users,代码行数:25,代码来源:mixins.py

示例2: send

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def send(self):
        result = None
        self.recipient = self.recipient.strip()

        try:
            validate_phone_number(self.recipient)
            result = self.send_sms()
        except ValidationError:
            pass

        try:
            validate_email(self.recipient)
            result = self.send_mail()
        except ValidationError:
            pass

        self.save()
        return result 
开发者ID:fpsw,项目名称:Servo,代码行数:20,代码来源:note.py

示例3: test_with_invalid_average_progress

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_with_invalid_average_progress(self, average_progress):
        """
        Apparently Django models don't validate automatically on save
        """
        assert average_progress < 0 or average_progress > 1
        rec = dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            enrollment_count=11,
            active_learners_today=1,
            average_progress=average_progress,
            average_days_to_complete=5,
            num_learners_completed=10
        )
        obj = CourseDailyMetrics(**rec)
        with pytest.raises(ValidationError) as execinfo:
            obj.clean_fields()

        assert 'average_progress' in execinfo.value.message_dict 
开发者ID:appsembler,项目名称:figures,代码行数:22,代码来源:test_course_daily_metrics_model.py

示例4: clean

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def clean(self):
        if self.batch_file and self.batch_file.file:
            csvfile = csv.DictReader(self.batch_file.file, delimiter="\t")
            row = csvfile.next()
            for field in self.core_fields:
                if field not in row.keys():
                    raise ValidationError('CSV File does not have the necessary field: '+ field)

            uris = []
            for row in csvfile:
                fcode = row.get("FEATURE_CODE")
                if not fcode:
                    raise ValidationError("A Feature code is missing")
                uri = row.get("URIS").split("|")[0]
                if not uri:
                    raise ValidationError('CSV file is missing a uri')
                if uri in uris:
                    raise ValidationError('duplicate URI detected')
            uris.append(uri) 
开发者ID:LibraryOfCongress,项目名称:gazetteer,代码行数:21,代码来源:models.py

示例5: exception_handler

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    Adds support the DRF default to also handle django.core.exceptions.ValidationError

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    response = original_exception_handler(exc, context)

    if response:
        return response

    elif isinstance(exc, DjangoValidationError):
        data = {"messages": exc.messages}
        set_rollback()
        return Response(data, status=status.HTTP_400_BAD_REQUEST)

    return None 
开发者ID:mozilla,项目名称:normandy,代码行数:22,代码来源:views.py

示例6: test_unique_experiment_slug_update_collision

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_unique_experiment_slug_update_collision(self):
            action = ActionFactory(name="preference-experiment")
            arguments_a = PreferenceExperimentArgumentsFactory(
                slug="a", branches=[{"slug": "one"}]
            )
            arguments_b = PreferenceExperimentArgumentsFactory(
                slug="b", branches=[{"slug": "two"}]
            )
            # Does not throw when saving revisions
            RecipeFactory(action=action, arguments=arguments_a)
            recipe = RecipeFactory(action=action, arguments=arguments_b)

            with pytest.raises(serializers.ValidationError) as exc_info1:
                recipe.revise(arguments=arguments_a)
            error = action.errors["duplicate_experiment_slug"]
            assert exc_info1.value.detail == {"arguments": {"slug": error}} 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:test_models.py

示例7: test_no_duplicates

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_no_duplicates(self):
            action = ActionFactory(name="preference-rollout")
            arguments_a = {"slug": "a", "preferences": [{"preferenceName": "a", "value": "a"}]}
            arguments_b = {"slug": "b", "preferences": [{"preferenceName": "b", "value": "b"}]}
            RecipeFactory(action=action, arguments=arguments_a)
            recipe_b = RecipeFactory(action=action, arguments=arguments_b)
            expected_error = action.errors["duplicate_rollout_slug"]

            # Creating a new recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info1:
                RecipeFactory(action=action, arguments=arguments_a)
            assert exc_info1.value.detail == {"arguments": {"slug": expected_error}}

            # Revising an existing recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info2:
                recipe_b.revise(arguments=arguments_a)
            assert exc_info2.value.detail == {"arguments": {"slug": expected_error}} 
开发者ID:mozilla,项目名称:normandy,代码行数:19,代码来源:test_models.py

示例8: test_repeated_identical_survey_ids

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_repeated_identical_survey_ids(self):
        action = ActionFactory(name="show-heartbeat")
        arguments = {
            "repeatOption": "nag",
            "surveyId": "001",
            "message": "Message!",
            "learnMoreMessage": "More!?!",
            "learnMoreUrl": "https://example.com/learnmore",
            "engagementButtonLabel": "Label!",
            "thanksMessage": "Thanks!",
            "postAnswerUrl": "https://example.com/answer",
            "includeTelemetryUUID": True,
        }
        RecipeFactory(action=action, arguments=arguments)
        # Reusing the same "surveyId" should cause a ValidationError.
        # But you can change other things.
        arguments["message"] += " And this!"
        with pytest.raises(serializers.ValidationError) as exc_info:
            RecipeFactory(action=action, arguments=arguments)
        expected_error = action.errors["duplicate_survey_id"]
        assert exc_info.value.detail == {"arguments": {"surveyId": expected_error}} 
开发者ID:mozilla,项目名称:normandy,代码行数:23,代码来源:test_models.py

示例9: is_valid

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def is_valid(self, raise_exception=False):
        super().is_valid(raise_exception=raise_exception)

        if "xpi" in self.validated_data:
            try:
                Extension(**self.validated_data).populate_metadata()
            except DjangoValidationError as ex:
                self._validated_data = {}

                for field in ex.message_dict:
                    self._errors.update({field: ex.message_dict[field][0]})

        if self._errors and raise_exception:
            raise ValidationError(self.errors)

        return not bool(self._errors) 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:serializers.py

示例10: clean

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def clean(self):
        if not self.bid.istarget:
            raise ValidationError('Target bid must be a leaf node')
        self.donation.clean(self)
        from .. import viewutil

        bidsTree = (
            viewutil.get_tree_queryset_all(Bid, [self.bid])
            .select_related('parent')
            .prefetch_related('options')
        )
        for bid in bidsTree:
            if bid.state == 'OPENED' and bid.goal is not None and bid.goal <= bid.total:
                bid.state = 'CLOSED'
                if hasattr(bid, 'dependent_bids_set'):
                    for dependentBid in bid.dependent_bids_set():
                        if dependentBid.state == 'HIDDEN':
                            dependentBid.state = 'OPENED'
                            dependentBid.save() 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:21,代码来源:bid.py

示例11: test_bid_suggestion_name_length

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_bid_suggestion_name_length(self):
        parent_bid = models.Bid(name='Parent bid', speedrun=self.run)

        # A suggestion for a parent bid with no max length should be okay
        child = models.Bid(parent=parent_bid, name='quite a long name')
        child.clean()

        # A suggestion with a too long name should fail validation
        parent_bid.option_max_length = 5
        child = models.Bid(parent=parent_bid, name='too long')
        with self.assertRaises(ValidationError):
            child.clean()

        # A suggestion with okay name should pass validation
        child = models.Bid(parent=parent_bid, name='short')
        child.clean() 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:18,代码来源:test_bid.py

示例12: clean

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def clean(self):
        """Validate the BoardPermissions model.

        Check that the read permission is valid with respect to the relative to the global ACCOUNT_REQUIRED setting.
        Check that the other permissions are valid relative to
        """
        super(BoardPermissions, self).clean()

        errors = {}

        if getattr(settings, 'ACCOUNT_REQUIRED', True) and self.read_board == AuthLevels.collaborators.anyone.key:
            errors['read_board'] = _('Cannot set permission to public because site permits only registered users')
        if self.add_comments > self.read_comments:
            errors['add_comments'] = _('Cannot be more permissive than the "read comments" permission')
        if self.edit_elements > self.add_elements:
            errors['edit_elements'] = _('Cannot be more permissive than the "add elements" permission')
        if self.read_comments > self.read_board:
            errors['read_comments'] = _('Cannot be more permissive than the "read board" permission')
        if self.add_elements > self.read_board:
            errors['add_elements'] = _('Cannot be more permissive than the "read board" permission')
        if self.edit_board > self.edit_elements:
            errors['edit_board'] = _('Cannot be more permissive than the "edit elements" permission')

        if len(errors) > 0:
            raise ValidationError(errors) 
开发者ID:twschiller,项目名称:open-synthesis,代码行数:27,代码来源:models.py

示例13: add_view

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def add_view(self, request, form_url='', extra_context=None):
        site_id = request.GET.get('site_id', None)

        if not site_id:
            return self.select_site_view(request)
        else:
            try:
                site_id = self.model._meta.pk.to_python(site_id)
                site = Site.objects.get(pk=site_id)
            except (Site.DoesNotExist, ValidationError, ValueError):
                return self.select_site_view(request)
            else:
                try:
                    obj = self.model.objects.get(site=site)
                    change_url = reverse(
                        'admin:%s_%s_change' % self.get_model_info(), args=(obj.pk,),
                        current_app=self.admin_site.name)
                    msg = _('{0} for "{1}" already exists. You may edit it below.')\
                        .format(self.opts.verbose_name, site.domain)
                    self.message_user(request, msg)
                    return HttpResponseRedirect(change_url)
                except self.model.DoesNotExist:
                    pass
        return super(SettingsAdmin, self).add_view(request, form_url, extra_context) 
开发者ID:mishbahr,项目名称:django-usersettings2,代码行数:26,代码来源:admin.py

示例14: _sort_by

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def _sort_by(self, datum, param, path=None):
        """
        Key function that is used for results sorting. This is passed as argument to `sorted()`
        """
        if not path:
            path = []
        try:
            if '__' in param:
                root, new_param = param.split('__')
                path.append(root)
                return self._sort_by(datum[root], param=new_param, path=path)
            else:
                path.append(param)

            data = datum[param]
            if isinstance(data, list):
                raise ValidationError(self._list_attribute_error.format(param))
            return data
        except TypeError:
            raise ValidationError(self._list_attribute_error.format('.'.join(path)))
        except KeyError:
            raise ValidationError('Invalid sorting field: {}'.format('.'.join(path))) 
开发者ID:MattBroach,项目名称:DjangoRestMultipleModels,代码行数:24,代码来源:mixins.py

示例15: test_no_queryset

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ValidationError [as 别名]
def test_no_queryset(self):
        """
        A querylist with no `queryset` key should raise a ValidationError with the
        appropriate message
        """
        view = NoQuerysetView.as_view()

        request = factory.get('/')

        with self.assertRaises(ValidationError) as error:
            view(request).render()

        self.assertEqual(error.exception.message, (
            'All items in the NoQuerysetView querylist attribute '
            'should contain a `queryset` key'
        )) 
开发者ID:MattBroach,项目名称:DjangoRestMultipleModels,代码行数:18,代码来源:test_object_view.py


注:本文中的django.core.exceptions.ValidationError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。