Python django.core.exceptions.ValidationError() Examples
The following are 30
code examples of django.core.exceptions.ValidationError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.exceptions
, or try the search function
.
Example #1
Source File: mixins.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 7 votes |
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})
Example #2
Source File: note.py From Servo with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #3
Source File: test_object_view.py From DjangoRestMultipleModels with MIT License | 6 votes |
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' ))
Example #4
Source File: test_course_daily_metrics_model.py From figures with MIT License | 6 votes |
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
Example #5
Source File: models.py From gazetteer with MIT License | 6 votes |
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)
Example #6
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
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
Example #7
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 6 votes |
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}}
Example #8
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 6 votes |
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}}
Example #9
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 6 votes |
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}}
Example #10
Source File: serializers.py From normandy with Mozilla Public License 2.0 | 6 votes |
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)
Example #11
Source File: bid.py From donation-tracker with Apache License 2.0 | 6 votes |
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()
Example #12
Source File: bid.py From donation-tracker with Apache License 2.0 | 6 votes |
def clean(self): sameBid = BidSuggestion.objects.filter( Q(name__iexact=self.name) & ( Q(bid__event=self.bid.get_event()) | Q(bid__speedrun__event=self.bid.get_event()) ) ) if sameBid.exists(): if sameBid.count() > 1 or sameBid[0].id != self.id: raise ValidationError( 'Cannot have a bid suggestion with the same name within the same event.' ) # If set, limit the length of suggestions based on the parent bid's # setting
Example #13
Source File: test_bid.py From donation-tracker with Apache License 2.0 | 6 votes |
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()
Example #14
Source File: models.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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)
Example #15
Source File: admin.py From django-usersettings2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #16
Source File: mixins.py From DjangoRestMultipleModels with MIT License | 6 votes |
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)))
Example #17
Source File: forms.py From donation-tracker with Apache License 2.0 | 5 votes |
def clean_keys(self): keys = {k.strip() for k in self.cleaned_data['keys'].split('\n') if k.strip()} if models.PrizeKey.objects.filter(key__in=keys).exists(): raise ValidationError('At least one key already exists.') return keys
Example #18
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 5 votes |
def test_legacy_bad_install_rdf(self): xpi = LegacyAddonFileFactory(signed=False) xpi.add_file("install.rdf", b"{}") with pytest.raises(ValidationError) as exc: ExtensionFactory(xpi__from_func=xpi.open) assert len(exc.value.error_dict["xpi"]) == 1 assert exc.value.error_dict["xpi"][0].message == 'Legacy addon "install.rdf" is corrupt.'
Example #19
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 5 votes |
def test_webext_no_version(self): xpi = WebExtensionFileFactory() manifest = xpi.manifest del manifest["version"] xpi.replace_manifest(manifest) with pytest.raises(ValidationError) as exc: ExtensionFactory(xpi__from_func=xpi.open) assert len(exc.value.error_dict["xpi"]) == 1 assert ( exc.value.error_dict["xpi"][0].message == 'Web extensions must have a manifest key "version".' )
Example #20
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 5 votes |
def test_webext_no_id(self): xpi = WebExtensionFileFactory(signed=False, overwrite_data={"applications": {"gecko": {}}}) with pytest.raises(ValidationError) as exc: ExtensionFactory(xpi__from_func=xpi.open) assert len(exc.value.error_dict["xpi"]) == 1 assert ( exc.value.error_dict["xpi"][0].message == 'Web extensions must have a manifest key "applications.gecko.id".' )
Example #21
Source File: test_models.py From normandy with Mozilla Public License 2.0 | 5 votes |
def test_legacy_no_id(self): xpi = LegacyAddonFileFactory(overwrite_data={"id": ""}, signed=False) with pytest.raises(ValidationError) as exc: ExtensionFactory(xpi__from_func=xpi.open) assert len(exc.value.error_dict["xpi"]) == 1 assert ( exc.value.error_dict["xpi"][0].message == 'Legacy addons "install.rdf" must specify an id.' )
Example #22
Source File: fields.py From donation-tracker with Apache License 2.0 | 5 votes |
def __call__(self, value): super(TimestampValidator, self).__call__(value) h, m, s, ms = re.match(self.regex, str(value)).groups() if h is not None and int(m) >= 60: raise ValidationError( 'Minutes cannot be 60 or higher if the hour part is specified' ) if m is not None and int(s) >= 60: raise ValidationError( 'Seconds cannot be 60 or higher if the minute part is specified' )
Example #23
Source File: prize.py From donation-tracker with Apache License 2.0 | 5 votes |
def clean(self, winner=None): if self.maxmultiwin > 1 and self.category is not None: raise ValidationError( { 'maxmultiwin': 'A donor may not win more than one prize of any category, so setting a prize ' 'to have multiple wins per single donor with a non-null category is incompatible.' } ) if (not self.startrun) != (not self.endrun): raise ValidationError( {'startrun': 'Must have both Start Run and End Run set, or neither.'} ) if self.startrun and self.event != self.startrun.event: raise ValidationError( {'event': 'Prize Event must be the same as Start Run Event'} ) if self.endrun and self.event != self.endrun.event: raise ValidationError( {'event': 'Prize Event must be the same as End Run Event'} ) if self.startrun and self.startrun.starttime > self.endrun.starttime: raise ValidationError( {'startrun': 'Start Run must begin sooner than End Run'} ) if (not self.starttime) != (not self.endtime): raise ValidationError( {'starttime': 'Must have both Start Time and End Time set, or neither'} ) if self.starttime and self.starttime > self.endtime: raise ValidationError( {'starttime': 'Prize Start Time must be later than End Time'} ) if self.startrun and self.starttime: raise ValidationError( {'starttime': 'Cannot have both Start/End Run and Start/End Time set'} )
Example #24
Source File: prize.py From donation-tracker with Apache License 2.0 | 5 votes |
def check_multiwin(self, value): if value > self.prize.maxmultiwin: raise ValidationError( 'Count must not exceed the prize multi win amount ({0})'.format( self.prize.maxmultiwin ) ) return value
Example #25
Source File: prize.py From donation-tracker with Apache License 2.0 | 5 votes |
def validate_unique(self, **kwargs): if ( 'winner' not in kwargs and 'prize' not in kwargs and self.prize.category is not None ): for prizeWon in PrizeWinner.objects.filter( prize__category=self.prize.category, winner=self.winner, prize__event=self.prize.event, ): if prizeWon.id != self.id: raise ValidationError( 'Category, winner, and prize must be unique together' )
Example #26
Source File: tests.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_validate_reverse_org_relation(self): org1 = self._create_org(name='org1') org2 = self._create_org(name='org2') t = Template.objects.create(name='test-t', organization=org1) Config.objects.create(name='test-c1', template=t, organization=org1) with self.assertRaises(ValidationError): t.organization = org2 t.full_clean()
Example #27
Source File: tests.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_validate_org_relation_error(self): org = self._create_org() t = Template.objects.create(name='test', organization=org) c = Config(name='test', template=t) with self.assertRaises(ValidationError): c.full_clean()
Example #28
Source File: donation.py From donation-tracker with Apache License 2.0 | 5 votes |
def clean(self, bid=None): super(Donation, self).clean() if self.domain == 'LOCAL': # local donations are always complete, duh if not self.donor: raise ValidationError('Local donations must have a donor') self.transactionstate = 'COMPLETED' if not self.donor and self.transactionstate != 'PENDING': raise ValidationError( 'Donation must have a donor when in a non-pending state' ) if not self.domainId and self.donor and self.timereceived: self.domainId = ( str(calendar.timegm(self.timereceived.timetuple())) + self.donor.email ) bids = set(self.bids.all()) # because non-saved bids will not have an id, they are not hashable, so we have to special case them if bid: if not bid.id: bids = list(bids) + [bid] else: # N.B. the order here is very important, as we want the new copy of bid to override the old one (if present) bids = list({bid} | bids) bids = [b.amount or 0 for b in bids] bidtotal = reduce(lambda a, b: a + b, bids, Decimal('0')) if self.amount and bidtotal > self.amount: raise ValidationError( 'Bid total is greater than donation amount: %s > %s' % (bidtotal, self.amount) ) # TODO: language detection again? self.commentlanguage = 'un'
Example #29
Source File: event.py From donation-tracker with Apache License 2.0 | 5 votes |
def validate_unique(self, exclude=None): case_insensitive = Runner.objects.filter(name__iexact=self.name) if self.id: case_insensitive = case_insensitive.exclude(id=self.id) case_insensitive = case_insensitive.exists() try: super(Runner, self).validate_unique(exclude) except ValidationError as e: if case_insensitive: e.error_dict.setdefault('name', []).append( self.unique_error_message(Runner, ['name']) ) raise if case_insensitive: raise self.unique_error_message(Runner, ['name'])
Example #30
Source File: event.py From donation-tracker with Apache License 2.0 | 5 votes |
def clean(self): if self.id and self.id < 1: raise ValidationError('Event ID must be positive and non-zero') if not re.match(r'^\w+$', self.short): raise ValidationError('Event short name must be a url-safe string') if not self.scheduleid: self.scheduleid = None if ( self.donationemailtemplate is not None or self.pendingdonationemailtemplate is not None ): if not self.donationemailsender: raise ValidationError( 'Must specify a donation email sender if automailing is used' )