def clean(self): """Clean up data and set defaults""" c = self.cleaned_data if ('a' not in c or not c['a']) and c['q'] == '': raise ValidationError('Basic search requires a query string.') # Validate created and updated dates date_fields = (('updated', 'updated_date'), #('created', 'created_date'), ) for field_option, field_date in date_fields: if c[field_date] != '': try: created_timestamp = time.mktime( time.strptime(c[field_date], '%m/%d/%Y')) c[field_date] = int(created_timestamp) except (ValueError, OverflowError): c[field_option] = None else: c[field_option] = None # Empty value defaults to int c['num_votes'] = c.get('num_votes') or 0 return c
def validate_unique(self): """ Validates the uniqueness of fields, but also handles the localized_fields. """ form_errors = [] try: super(LocalisedForm, self).validate_unique() except ValidationError as e: form_errors += e.messages # add unique validation for the localized fields. localized_fields_checks = self._get_localized_field_checks() bad_fields = set() field_errors, global_errors = self._perform_unique_localized_field_checks( localized_fields_checks) bad_fields.union(field_errors) form_errors.extend(global_errors) for field_name in bad_fields: del self.cleaned_data[field_name] if form_errors: # Raise the unique together errors since they are considered # form-wide. raise ValidationError(form_errors)
class RichTextAreaField(RichTextField): post_save_listener = staticmethod(dependency_post_save_listener) src_text_attr = DEP_SRC_TEXT_ATTR #post_save_listener = staticmethod(post_save_listener) widget = widgets.RichTextAreaWidget default_error_messages = { 'syntax_error': _('Bad syntax in markdown formatting or template tags.'), 'invalid_object': _('Object does not exist or is not right inserted.'), 'invalid_tag': _('You can use only box template tag.'), 'url_error': _('Some links are invalid: %s.'), 'link_error': _('Some links are broken: %s.'), } def validate_rendered(self, rendered): """ Validate that the target text composes only of text and boxes """ from ella.core.templatetags.core import BoxNode, ObjectNotFoundOrInvalid try: t = Template(rendered) except TemplateSyntaxError, e: raise ValidationError(self.error_messages['syntax_error']) for n in t.nodelist: if isinstance(n, TextNode): continue elif isinstance(n, BoxNode): try: o = n.get_obj() except ObjectNotFoundOrInvalid, e: # TODO: pass lookup into error message # this raises UnicodeEncodeError # error_msg = self.error_messages['invalid_object'] % { # 'model': n.model._meta.verbose_name, # 'field': n.lookup[0], # 'value': n.lookup[1] #} raise ValidationError( self.error_messages['invalid_object']) else: raise ValidationError(self.error_messages['invalid_tag'])
def convert(self, sourcefile, targetfile): """Convert a video to h264 format using the magic script""" if convert_video(sourcefile, targetfile): return True else: errormsg = "Video conversion failed" raise ValidationError(errormsg)
def clean_datafile(self): ''' Clean datafile ''' f = self.cleaned_data['datafile'] valid_file, error = self.validate(f) if not valid_file: raise ValidationError("A problem occurred: %s" % error)
def clean_reason(self): """Assure that if a sample was completely split, the most recent process was indeed a split. """ reason = self.cleaned_data["reason"] if reason == "split" and not self.sample.last_process_if_split(): raise ValidationError(_("Last process wasn't a split.")) return reason
def clean_current_password(self): cleaned_data = self.cleaned_data current_password = cleaned_data.get('current_password', '') if not self.user.check_password(current_password): raise ValidationError('Wrong current password.') return current_password
def clean_user_activation_code(self): data = self.cleaned_data['user_activation_code'] if data != self.instance.activation_code: raise ValidationError( _('The validation code supplied by you does not match.')) return data
def clean(self): cleaned_data = super(PositionForm, self).clean() if not self.is_valid(): return cleaned_data if cleaned_data['active_from'] and cleaned_data['active_till']: if cleaned_data['active_from'] > cleaned_data['active_till']: raise ValidationError(_('Active till must be later than active from.')) return cleaned_data
def check_content_type(self): """ Check that the content type is supported. """ headers = self.cleaned_data['headers'] content_type = headers.get('content-type', '').strip() if not content_type: raise ValidationError( unicode(_("The server did not send a content type header."))) self.cleaned_data['content-type'] = content_type for prefix in settings.SUPPORTED_CONTENT_TYPES: if content_type.lower().startswith(prefix): break else: raise ValidationError(' '.join(( unicode(_("Unsupported content type: %s.")) % content_type, unicode(_("This service is for HTML or XHTML content.")))))
def clean_sender_title(self): name_parts = [] if self.cleaned_data['sender']: name_parts.append(self.cleaned_data['sender'].profile.display_name) if self.cleaned_data['sender_title']: name_parts.append(self.cleaned_data['sender_title']) if not name_parts: raise ValidationError("One of sender or title is required.")
def clean_timestamp(self): """Forbid timestamps that are in the future. """ timestamp = self.cleaned_data["timestamp"] if timestamp > datetime.datetime.now(): raise ValidationError( _("The timestamp must not be in the future.")) return timestamp
def validate_rendered(self, rendered): """ Validate that the target text composes only of text and boxes """ try: t = Template(rendered) except TemplateSyntaxError, e: raise ValidationError(self.error_messages['syntax_error'])
def clean(self): d = super(ListingForm, self).clean() if not self.is_valid(): return d if d['publish_to'] and d['publish_from'] > d['publish_to']: raise ValidationError( _('Publish to must be later than publish from.')) return d
def clean (self, value): if value is None or value == '': value = 'null' super(HstoreField, self).clean(value) try: value = simplejson.loads(value) except ValueError: raise ValidationError(self.error_messages['invalid']) return value
def clean_layer_type(self): """Assure that the hidden fixed string ``layer_type`` truely is ``"clustertoolhotwirelayer"``. When using a working browser, this should always be the case, no matter what the user does. However, it must be checked nevertheless because other clients may send wrong data. """ if self.cleaned_data["layer_type"] != self.type: raise ValidationError("Layer type must be “hot-wire”.") return self.cleaned_data["layer_type"]
def clean (self, value): super(JSONField, self).clean(value) if value is None or value == '': return { } try: value = simplejson.loads(value) except ValueError: raise ValidationError( self.error_messages['invalid'] ) return value
def clean(self, value): cvalue = super(CategoryChoiceField, self).clean(value) return cvalue # TODO unable to realize if field was modified or not (when user has view permission a hits Save.) # Permissions checks are placed in FormSets for now. CategoryChoiceField restricts category # choices at the moment. # next part is category-based permissions (only for objects with category field) # attempt: to do role-permission checks here (add new and change permissions checking) # Adding new object #TODO check wheter field was modified or not. add_perm = get_permission('add', self.model) if not has_category_permission(self.user, cvalue, add_perm): raise ValidationError(_('Category not permitted')) # Changing existing object change_perm = get_permission('change', self.model) if not has_category_permission(self.user, cvalue, change_perm): raise ValidationError(_('Category not permitted')) return cvalue
def clean(self, value): value = forms.CharField.clean(self, value) if not re.match( r'^[A-Za-z0-9_.]+-[A-Za-z0-9_.]+-[A-Za-z0-9_.]+(-[A-Za-z0-9_.]+)?$', value): raise ValidationError("Name isn't formatted appropriately") if value != NameField.existing_ok_name: try: old = System.objects.get(name=value) except System.DoesNotExist: old = None if old: raise ValidationError("Name is already in use") return value
def clean(self, value): if not value and not self.required: return None value = super(ZipFileField, self).clean(value) if isinstance(value, UploadedFile) and \ value.size <= self.max_size \ and is_zipfile(value): return value raise ValidationError('Not a zip file.')
def clean_user_activation_code(self): myfield = self.base_fields['user_activation_code'] value = myfield.widget.value_from_datadict( self.data, self.files, self.add_prefix('user_activation_code')) user_activation_code = myfield.clean(value) if user_activation_code != self.instance.activation_code: raise ValidationError( _('The validation code supplied by you does not match.'))
def compress(self, data_list): if len(data_list) == 0: return None if data_list[0] == OTHER_VAL: return data_list[1] else: if data_list[1]: raise ValidationError("Either select from the drop-down or select %s" % OTHER_PRES) return data_list[0]
def clean(self): cleaned_data = self.cleaned_data password = cleaned_data.get('password', '') retyped_password = cleaned_data.get('retyped_password', '') if password != retyped_password: raise ValidationError('Password and retyped password didn\'t match.') return cleaned_data
def split_url(self): """ Parse URL into components. """ url = self.cleaned_data['url'] self.url_parts = list(urlparse.urlsplit(url, 'http')) # print self.url_parts if self.url_parts[0] not in SUPPORTED_SCHEMES: raise ValidationError( unicode(_("URL scheme %(scheme)s is not supported.") % {'scheme': self.url_parts[0]})) self.netloc_parts = split_netloc(self.url_parts[1]) if not self.url_parts[1] or not self.netloc_parts[2]: raise ValidationError( unicode(_("Malformed URL (server name not specified)."))) if '%20' in self.netloc_parts[2]: raise ValidationError( unicode(_("Malformed URL (spaces in server name).")))
def clean(self, value): """ cleans the selected id to a model in model_list""" try: return self.qs.filter(pk=int(value))[0] except IndexError: raise ValidationError( ugettext( u'Select a valid choice. That choice is not one of the available choices.' ))
def clean_email(self): userId = self.data['userId'] email = self.data['email'].lower() try: user = User.objects.get(email__exact=email) if int(user.userId) != int(userId): raise ValidationError('Email address already exists') except User.DoesNotExist: pass
class Safe_URLField(URLField): default_error_messages = { 'M': _(u"""<strong>For Malware Detection:</strong><br /><br /><hr/> """ """This page appears to contain malicious code that could be """ """"downloaded to your computer without your consent. You can """ """"learn more about harmful web content including viruses and """ """other malicious code and how to protect your computer at """ """<a href="http://stopbadware.org">StopBadware.org</a>.<br /> """ """"<br />Advisory Provided by Google: """ """<a href="http://code.google.com/support/bin/answer.py?answer=70015"> """ """"Check http://code.google.com/support/bin/answer.py?answer=70015</a>""" """<br /><br /><a href="http://www.google.com/">Google</a> works """ """to provide the most accurate and uptodate phishing and malware """ """information.However, it cannot guarantee that its information """ """is comprehensive and errorfree: some risky sites may not be """ """identified, and some safe sites may be identified in error."""), 'B': _(u"""<strong>For Blacklist Detection:</strong><br /><br /><hr />""" """This page may be a forgery or imitation of another website, """ """designed to trick users into sharing personal or financial """ """information. Entering any personal information on this page """ """may result in identity theft or other abuse. You can find out """ """more about phishing from <a href="http://www.antiphishing.org/">""" """www.antiphishing.org</a>.<br /><br />Advisory Provided by Google: """ """Check <a href="http://code.google.com/support/bin/answer.py?answer=70015">""" """http://code.google.com/support/bin/answer.py?answer=70015</a><br /><br />""" """<a href="http://www.google.com/">Google</a> works to provide the most """ """accurate and uptodate phishing and malware information.However, """ """it cannot guarantee that its information is comprehensive and """ """errorfree: some risky sites may not be identified, and some """ """"safe sites may be identified in error."""), } def __init__(self, max_length=2048, min_length=None, badware_check=True, *args, **kwargs): self.badware_check = badware_check super(Safe_URLField, self).__init__(max_length, min_length, *args,**kwargs) def clean(self, value): import urllib2 if value == u'': return value if value and '://' not in value: value = u'http://%s' % value lookup_site = getattr(settings, 'BADWARE_SITE', "http://thejaswi.info/projects/" "safe_browsing/badware_check/?badware_url=%s" %value) req = urllib2.Request(lookup_site, None, {"User-Agent":settings.URL_VALIDATOR_USER_AGENT}) try: contents = urllib2.urlopen(req).read() except urllib2.URLError,e: raise ValidationError(unicode(e)) if not contents in self.default_error_messages.keys(): value = super(Safe_URLField, self).clean(value) return value else: raise ValidationError(self.error_messages[contents])
def clean_file(self): value = self.cleaned_data.get('file', None) if not value or not value[0]: return value content = value[0] if not validate_file(content): raise ValidationError( _('The file is not a video file or has a format not supported') ) return value
def clean(self, value): value = (value or '').strip() or None if value is None: return if not self.required and not value: return try: value = Currency(value, parse_string=True) except NumberFormatError, e: raise ValidationError(e.message)
def clean(self, value): if not value and not self.required: return None # Trap cleaning errors & bubble them up as JSON errors try: return super(JSONFormFieldBase, self).clean(value) except TypeError: raise ValidationError(_("Enter valid JSON"))