當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。