Here are the examples of the python api django.core.exceptions.ValidationError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
200 Examples
3
Example 1
View licensedef prepare_others(self, value): keys = get_unambiguous_fields(self.model_class) if len(keys) == 1: key = keys[0] if self.related_field == 'id': fk_dic = {key: value} self.persistence = [key] else: fk_dic = {self.related_field: value} self.persistence = [self.related_field] return super(FkInstanceGenerator, self).prepare(fk_dic) else: raise ValidationError( 'Failure to identify unambiguous fields for {}' ''.format(self.model_class))
3
Example 2
View licensedef clean(self): document = self.invoice or self.proforma if document: if document.provider != self.provider: raise ValidationError( 'Provider doesn\'t match with the one in documents.' ) if document.customer != self.customer: raise ValidationError( 'Customer doesn\'t match with the one in documents.' ) if self.invoice and self.proforma: if self.invoice.proforma != self.proforma: raise ValidationError('Invoice and proforma are not related.')
3
Example 3
View licensedef clean(self): if self.presale_start and self.presale_end and self.presale_start > self.presale_end: raise ValidationError({'presale_end': _('The end of the presale period has to be later than its start.')}) if self.date_from and self.date_to and self.date_from > self.date_to: raise ValidationError({'date_to': _('The end of the event has to be later than its start.')}) super().clean()
3
Example 4
View licensedef clean(self): if self.max_words and len(self.text.split()) > self.max_words: raise ValidationError("Sponsorship level only allows for %s " "words." % self.max_words) editable_fields = self.data_fields() if bool(self.text) and 'text' not in editable_fields: raise ValidationError("Benefit type %s may not have text" % self.benefit.type) if bool(self.upload) and 'upload' not in editable_fields: raise ValidationError("Benefit type %s may not have an uploaded " "file (%s)" % (self.benefit.type, self.upload))
3
Example 5
View licensedef clean(self): try: __ = self.url except NoReverseMatch: raise ValidationError(_('Not valid slug for AdPage')) super(AdPage, self).clean()
3
Example 6
View licensedef clean_email(self): # check for uniqueness of email address if get_user_model().objects.filter(is_active=True, email=self.cleaned_data['email']).exists(): msg = _("A customer with the e-mail address ‘{email}’ already exists.\n" "If you have used this address previously, try to reset the password.") raise ValidationError(msg.format(**self.cleaned_data)) return self.cleaned_data['email']
3
Example 7
View licensedef clean_fields(self, exclude=None): errors = {} if 'field_name' not in exclude: if not re.match('\w[\w\d_]*$', self.field_name): errors['field_name'] = [_('This is no valid name')] if 'dynamicfield' not in exclude: if self.field_name in self.dynamicform.base_form_class.base_fields and self.dynamicfield is not None: errors['dynamicfield'] = [_("This field can not be overridden; leave the field empty")] elif self.field_name not in self.dynamicform.base_form_class.base_fields and self.dynamicfield is None: errors['dynamicfield'] = [_("This field is not predefined; don't leave the field empty")] if errors: raise ValidationError(errors)
3
Example 8
View licensedef clean(self, value): """ Validates that the input can be compiled as a template. """ value = super(TemplateFormField, self).clean(value) from django.template import Template, TemplateSyntaxError try: Template(value) except TemplateSyntaxError, error: raise ValidationError(error) return value
3
Example 9
View licensedef clean(self, value): if value in self.empty_values: return try: id_value = int(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}) try: user = User.get_user(id=id_value) except User.DoesNotExist: raise ValidationError(self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}) return user
3
Example 10
View licensedef validate(self, value, model_instance): arr_choices = self.get_choices_selected(self.get_choices_default()) for opt_select in value: if (opt_select not in arr_choices): raise exceptions.ValidationError( self.error_messages['invalid_choice'] % value) return
3
Example 11
View licensedef validate(self, value, model_instance): "Validate choice workflow" if model_instance.id: db_value = self.get_db_value(model_instance) if not self.choices.validate(getattr(db_value, self.name), value): raise exceptions.ValidationError(_('%s %s' % (self.choices.error_msg, self.choices.get_value(value)))) super(FlowIntegerField, self).validate(value, model_instance)
3
Example 12
View licensedef validate_website(value): try: headers = {'User-Agent': ('Mozilla/5.0 (Windows NT 5.1) ' 'AppleWebKit/537.11 ' '(KHTML like Gecko) ' 'Chrome/23.0.1271.95 Safari/537.11')} req = urllib2.Request(value, None, headers) urllib2.urlopen(req) except (urllib2.URLError, ValueError): raise ValidationError(u'That url appears not to work.')
3
Example 13
View licensedef clean(self): ''' Perform some additional validations ''' if (not self.time_end and self.time_start) or (self.time_end and not self.time_start): raise ValidationError(_("If you enter a time, you must enter both start and end time.")) if self.time_end and self.time_start and self.time_start > self.time_end: raise ValidationError(_("The start time cannot be after the end time."))
3
Example 14
View licensedef run_validators(self, value): if value in validators.EMPTY_VALUES: return errors = [] for v in self.validators: try: v(value) except ValidationError, e: if hasattr(e, 'code') and e.code in self.error_messages: message = self.error_messages[e.code] if e.params: message = message % e.params errors.append(message) else: errors.extend(e.messages) if errors: raise ValidationError(errors)
3
Example 15
View licensedef validate_color(value): if not re.match(r'^[0-9a-fA-F]{6}$', value): raise ValidationError( _('%(value)s is not a valid color.'), params={'value': value}, )
3
Example 16
View licensedef clean_phone(self): phone = self.cleaned_data.get('phone', None) # clean phone by removing all non-numerals phone = ''.join(x for x in phone if x.isdigit()) ph_length = str(phone) min_length = 10 max_length = 13 if len(ph_length) < min_length: raise ValidationError('Must be 10 digit phone number.') if len(ph_length) > max_length: raise ValidationError('Must be at maxium 13 digits long') return phone
3
Example 17
View licensedef validate_contact(value): errors = [] if not isinstance(value, list): value = (value, ) for item in value: try: validate_json(item, SCHEMA_CONTACT) except JsonValidationError as e: errors.append(e) if errors: raise ValidationError(errors)
3
Example 18
View licensedef save(self, *args, **kwargs): """ Sync with Google Website Optimizer The local_only=True keyword argument will prevent syncing the item with Google Website Optimizer's API """ from django.core.exceptions import ValidationError if self.gwo_experiment != self.gwo_section.gwo_experiment: raise ValidationError("The experiment and the section don't go together!") if not kwargs.pop('local_only', False): self._sync_gwo_variation() super(GwoVariation, self).save(*args, **kwargs)
3
Example 19
View licensedef is_map_file(field): content = field.read() if content[:4] not in ('DATA', 'ATAD'): raise ValidationError("It's not a valid Teeworlds map file.") if content[4] != '\x04': raise ValidationError("This map file version is not supported by Teerace" " (0.5 or 0.6 is required).")
3
Example 20
View licensedef clean(self): if self.width and not CSS_WIDTH_RE.match(self.width): raise ValidationError( _('Width must be a positive integer followed by "px" or "%".') ) if self.height and not CSS_HEIGHT_RE.match(self.height): raise ValidationError( _('Height must be a positive integer followed by "px".') ) if self.style: try: json.loads(self.style) except ValueError: raise ValidationError(_('Map styling has to be valid JSON.'))
3
Example 21
View licensedef email_validator(value): """ Validates given email in terms of uniqeness and correctness. """ if User.objects.filter(email=value).exists(): raise ValidationError(u'Email already exists') else: validate_email(value)
3
Example 22
View licensedef clean(self): if self.parent: if not self.type: self.type = self.parent.type elif self.type != self.parent.type: raise ValidationError(_('The type does not match the model parents type')) elif not self.type: raise ValidationError(_('Root accounts must define a type'))
3
Example 23
View licensedef validate_json(value): """Validates a JSON snippet. """ try: json.loads(value) except: raise ValidationError(_('Ivalid JSON syntax'))
3
Example 24
View licensedef validate(self, value, model_instance): arr_choices = self.get_choices_selected(self.get_choices_default()) for opt_select in value: if (opt_select not in arr_choices): if django.VERSION[0] == 1 and django.VERSION[1] >= 6: raise exceptions.ValidationError( self.error_messages['invalid_choice'] % {"value": value}) else: raise exceptions.ValidationError( self.error_messages['invalid_choice'] % value)
3
Example 25
View licensedef send_message(self, sender, recipient, message): """ Send a new message :param sender: user :param recipient: user :param message: String :return: Message and status code """ if sender == recipient: raise ValidationError("You can't send messages to yourself.") message = Message(sender=sender, recipient=recipient, content=str(message)) message.save() message_sent.send(sender=message, from_user=message.sender, to=message.recipient) # The second value acts as a status value return message, 200
3
Example 26
View licensedef validate_unique(self, exclude=None): """ Checks unique constraints on the model and raises ``ValidationError`` if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors = self._perform_date_checks(date_checks) for k, v in date_errors.items(): errors.setdefault(k, []).extend(v) if errors: raise ValidationError(errors)
3
Example 27
View licensedef to_python(self, value): # psycopg2 already supports array types, so we don't actually need to serialize # or deserialize if value is None: return None if not isinstance(value, (list, tuple, set, deque,)): try: iter(value) except TypeError: raise ValidationError("An ArrayField value must be None or an iterable.") s = super(ArrayFieldBase, self) return [s.to_python(x) for x in value]
3
Example 28
View licensedef link_validator(value): """Validates the given link.""" try: resolve_link(value) except LinkResolutionError: raise ValidationError("Enter a valid URL.")
3
Example 29
View licensedef clean_accept_pysv_conferences(self): value = self.cleaned_data['accept_pysv_conferences'] if not value and self.instance.accept_pysv_conferences: self.data['accept_pysv_conferences'] = True raise ValidationError(_("You previously agreed to this option" " which can no longer be revoked.")) return value
3
Example 30
View licensedef validate_phone(value): if (value.startswith('+')): value = value[1:] if (len(value) < 6 or (not value.isdigit())): raise ValidationError( _('%(value)s is not a phone number'), params={'value': value},)
3
Example 31
View licensedef put(self, request, app_label, object_name, object_pk): obj = self.get_object(app_label, object_name, object_pk) if not self.site.has_change_permission(request, obj): raise PermissionDenied(_("You don't have permission to edit this widget.")) data = self.data()['attributes'] form = obj.get_form(request, data=data) if not form.is_valid(): raise ValidationError(form.errors) form.save() return self.render_to_response(form.instance.to_json(self.site), status=200)
3
Example 32
View licensedef clean(self): """ Validates that either a user or an invited_user is set. """ if not self.type: raise ValidationError('Account type is required.')
3
Example 33
View licensedef to_python(self, value): """ Convert the input JSON value into python structures, raises django.core.exceptions.ValidationError if the data can't be converted. """ if self.blank and not value: return None if isinstance(value, six.string_types): try: return simplejson.loads(value) except Exception as e: raise ValidationError(str(e)) else: return value
3
Example 34
View licensedef clean_key(self): key = None try: key = self.get_key_object() except: raise ValidationError("Invalid SSH key")
3
Example 35
View licensedef __call__(self, value): parsed = urlparse(value) if parsed.scheme not in ("http", "https"): raise ValidationError(message=self.message) if parsed.hostname in ("127.0.0.1", "localhost"): raise ValidationError(message=self.message)
3
Example 36
View licensedef _patch_clean(model): old_clean = model.clean # Call the original clean method to avoid losing validations def clean(self): old_clean(self) errors = _validate_slugs(self) if errors: raise ValidationError(errors) model.clean = clean
3
Example 37
View licensedef clean(self): if self.start_date and self.end_date: if self.start_date > self.end_date: raise ValidationError({"start_date": _("Start date must be " "before end date."), "end_date": _("Start date must be " "before end date.")})
3
Example 38
View licensedef validate_unique(self, exclude=None): if not self.is_deleted and \ LibraryEntry.objects.exclude(pk=self.pk).filter( lib_id=self.lib_id, library=self.library, is_deleted=False).exists(): raise ValidationError('Duplicated non-deleted lib ids for a player') super(LibraryEntry, self).validate_unique(exclude=exclude)
3
Example 39
View licensedef clean(self): query_set = Project.objects.exclude(pk=self.pk)\ .filter(name__iexact=self.name, organization=self.organization) if query_set.exists(): raise ValidationError(u'Project name "%s" is already in' u' use in this account.' % self.name.lower())
3
Example 40
View licensedef clean_fields(self, exclude=None): errors = {} if exclude is None: exclude = [] try: super(Area, self).clean_fields(exclude) except ValidationError as e: errors.update(e.message_dict) if errors: raise ValidationError(errors)
3
Example 41
View licensedef to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, )
3
Example 42
View licensedef clean(self): is_report_exist = Report.objects.filter( reporter=self.initial['reporter'], premise=self.initial['premise'], contention=self.initial['contention'], fallacy_type=self.cleaned_data['fallacy_type'] ).exists() if is_report_exist: raise ValidationError( u'You have already reported %s fallacy for this premise.' % ( self.cleaned_data['fallacy_type'] ) ) super(ReportForm, self).clean()
3
Example 43
View licensedef clean(self): if self.image: scaled_file = scale_image(self.image.file, IMG_MAX_SIZE) if not scaled_file: raise ValidationError(_(u'Cannot process image')) self.image.file = scaled_file
3
Example 44
View licensedef clean(self, value): if value == '': # Field was left blank. Make this None. value = 'None' try: return literal_eval(value) except (ValueError, SyntaxError): raise ValidationError(self.error_messages['invalid'])
3
Example 45
View licensedef clean(self): # if the object is being created, check the rate limits if self.pk: return # minute rate limit rate_minute = datetime.now() - timedelta(minutes=SHORTIM_RATELIMIT_MINUTE) minute_count = ShortURL.objects.filter(remote_user=self.remote_user, date__gte=rate_minute).count() if minute_count >= SHORTIM_RATELIMIT_MINUTE: raise ValidationError(_('Rate limit exceeded.')) # hour rate limit rate_hour = datetime.now() - timedelta(hours=SHORTIM_RATELIMIT_HOUR) hour_count = ShortURL.objects.filter(remote_user=self.remote_user, date__gte=rate_hour).count() if hour_count >= SHORTIM_RATELIMIT_HOUR: raise ValidationError(_('Rate limit exceeded.'))
3
Example 46
View licensedef clean(self): # Stores in formset.non_field_errors super(TopicPollChoiceInlineFormSet, self).clean() if not self.is_filled(): return forms_filled = [form for form in self.forms if form.is_filled()] if len(forms_filled) < 2: raise ValidationError(_("There must be 2 or more choices"))
3
Example 47
View licensedef validate_bp(value): bps = value.split() for bp in bps: members = bp.split("/") if len(members) != 2: raise ValidationError(u'Blueprints should be specified under' ' the form project/blueprint-name') (project, bpname) = list(members) if not _is_valid_lp_name(project): raise ValidationError(u'Incorrect project name: %s' % project) if not _is_valid_lp_name(bpname): raise ValidationError(u'Incorrect blueprint name: %s' % bpname) f = urllib.urlopen("https://api.launchpad.net/devel/%s/+spec/%s" % (project, bpname)) f.close() if f.getcode() != 200: raise ValidationError(u'No such blueprint: %s/%s' ' -- did you create it on Launchpad ?' % (project, bpname))
3
Example 48
View licensedef compress(self, data_list): if data_list: try: day, time, am_pm = (int(i) for i in data_list) except ValueError: raise ValidationError(self.error_messages['invalid']) if time == 12: if am_pm: # 12pm is noon am_pm = 0 else: # 12am is midnight time = 0 else: time = time + am_pm return datetime.datetime(1, 1, day + 1, time) # simple datetime # represent the day # of the week and the # hour to send return None
3
Example 49
View licensedef validate_dependency_version(value): if hasattr(settings, 'LOCAL_DEPENDENCY_OVERRIDE'): return # Disallow paths as versions if re.match(r'^file:|(\.*|~)/', value): raise ValidationError(_("Local path dependencies are not allowed"))
0
Example 50
View licensedef clean(self): self.has_changed_list = [] # Start by taking care of the contact object fields if self.cleaned_data.get('name') != self.instance.name: self.has_changed_list.append('Name') if self.cleaned_data.get('notes') != self.instance.notes: self.has_changed_list.append('Notes') if self.cleaned_data.get('should_surface') != self.instance.should_surface: self.has_changed_list.append('Send Contact Reminders') # Deal with deleted fields has_changed_list = [] for field_id in self.cleaned_data.get('deleted_fields', '').split(','): if field_id: try: field = ContactField.objects.get( contact=self.instance, id=field_id, ) has_changed_list.append(field.label) field.delete() except ContactField.DoesNotExist: pass # note_str = 'Deleted ' + ', '.join(has_changed_list) # LogEntry.objects.create( # contact = self.instance, # logged_by = self.user, # kind = 'edit', # notes = note_str, # ) # Prep the contact fields for saving self.instance.book = self.book document_items = None document_items = dict((key, value) for key, value in self.cleaned_data.items() if key.startswith('document')) self.document_field_dicts = {} pref_dict = { contact_constants.FIELD_TYPE_EMAIL: False, contact_constants.FIELD_TYPE_TWITTER: False, contact_constants.FIELD_TYPE_URL: False, contact_constants.FIELD_TYPE_PHONE: False, contact_constants.FIELD_TYPE_ADDRESS: False, } if document_items: for item in document_items: parts = item.split('_') field_id = parts[2] field_type = parts[1] field_dict = self.document_field_dicts.get(field_id, {}) field_dict['type'] = field_type if len(parts) == 3: field_dict['value'] = document_items[item] if len(parts) == 4: if parts[3] == 'label': field_dict['label'] = document_items[item] if parts[3] == 'pref': if document_items.get(item) and pref_dict.get(field_type): raise ValidationError( 'Only one {} can be preferred'.format(field_type), ) else: field_dict['pref'] = document_items[item] pref_dict[field_type] = True self.document_field_dicts[field_id] = field_dict return super(ContactForm, self).clean()