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_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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: models.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clean(self): if self.organization_user.organization.pk != self.organization.pk: raise ValidationError( { 'organization_user': _( 'The selected user is not member of this organization.' ) } )
Example #18
Source File: mixins.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _validate_org_reverse_relation(self, rel_name, field_error='organization'): """ prevents changing organization for existing objects which have relations specified by ``rel_name`` pointing to them, in order to prevent inconsistencies (relations belonging to different organizations) """ # do nothing on new objects, because they # cannot have relations pointing to them if self._state.adding: return old_self = self.__class__.objects.get(pk=self.pk) old_org = old_self.organization # org hasn't been changed, everything ok if old_org == self.organization: return rel = getattr(self, rel_name) count = rel.count() if count: rel_meta = rel.model._meta related_label = ( rel_meta.verbose_name if count == 1 else rel_meta.verbose_name_plural ) verb = _('is') if count == 1 else _('are') message = _( 'The organization of this {object_label} cannot be changed ' 'because {0} {related_object_label} {verb} still ' 'related to it'.format( count, object_label=self._meta.verbose_name, related_object_label=related_label, verb=verb, ) ) raise ValidationError({field_error: message})
Example #19
Source File: test_models.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_unique_email_validation(self): self._create_user(username='user1', email='same@gmail.com') options = {'username': 'user2', 'email': 'same@gmail.com', 'password': 'pass1'} u = self.user_model(**options) with self.assertRaises(ValidationError): u.full_clean()
Example #20
Source File: test_models.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_organization_owner_bad_organization(self): user = self._create_user(username='user1', email='abc@example.com') org1 = self._create_org(name='org1') org2 = self._create_org(name='org2') org_user = self._create_org_user(organization=org1, user=user) org_owner = self._create_org_owner() org_owner.organization = org2 org_owner.organization_user = org_user with self.assertRaises(ValidationError): org_owner.full_clean()
Example #21
Source File: tests.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_derived_model_template(self): c = Config(name='test') with self.assertRaises(ValidationError): c.full_clean()
Example #22
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 #23
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 #24
Source File: models.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clean(self): if self.name == "Intentional_Test_Fail": raise ValidationError('Intentional_Test_Fail') return self
Example #25
Source File: checkin.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_remote_device(request, sn): try: apple_sn_validator(sn) except ValidationError: return Device(sn=sn, image_url='https://static.servoapp.com/images/na.gif') get_gsx_connection(request) return Device.from_gsx(sn)
Example #26
Source File: product.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def clean_code(self): code = self.cleaned_data.get('code') if not re.match(r'^[\w\-/]+$', code): msg = _('Product code %s contains invalid characters') % code raise ValidationError(msg) return code
Example #27
Source File: note.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def validate_phone_number(number): match = re.match(r'([\+\d]+$)', number) if match: return match.group(1).strip() else: raise ValidationError(_(u'%s is not a valid phone number') % number)
Example #28
Source File: note.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def send_and_save(self, user): """ The main entry point to the sending logic """ from django.utils.encoding import force_text messages = list() recipients = [r.strip() for r in self.recipient.split(',')] for r in recipients: try: messages.append(self.send_sms(r, user)) except (ValidationError, IntegrityError), e: pass
Example #29
Source File: validators.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def apple_sn_validator(val): if validate(val.upper()) not in ('serialNumber', 'alternateDeviceId',): raise ValidationError(_(u'%s is not a valid serial or IMEI number') % val)
Example #30
Source File: validators.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def sn_validator(val): if not re.match(r'^\w*$', val): raise ValidationError(_('Serial numbers may only contain letters and numbers'))