def clean_contact(self): contact = self.cleaned_data['contact'] if not contact: return contact typ = self.cleaned_data['contact_type'] if typ == 'E': # email validators.validate_email(contact) elif typ in ['M', 'J']: # MUC or JID if typ == 'M': typname = 'MUC' else: typname = 'JID' if '@' not in contact or contact.count('@') > 1: raise ValidationError('Please enter a valid %s.' % typname) user, domain = contact.split('@') if not self.verify_domain(domain): raise ValidationError('Please enter a valid %s.' % typname) elif typ == 'W': # website parsed = urlparse(contact) if not (parsed.scheme and parsed.netloc): raise ValidationError('Please enter a valid URL.') else: raise ValidationError('no more cheese exception.') return contact
def clean(self, value): mac = value if mac and len(mac) != 17: raise ValidationError('MAC deve conter 17 caracteres.') elif mac: if len(mac.split(':')) != 6: raise ValidationError( 'MAC deve ser separado por dois pontos (:).') return mac
def clean_domain(self): try: domain = self.cleaned_data['domain'] if not self.verify_domain(domain): raise ValidationError( 'Domain must be a simple domain, i.e. "example.com"') except Exception: raise ValidationError("Could not parse domain.") return domain
def clean(self): " Validate that the template's activity don't overlap. " if not self.is_valid(): return # check that active_till datetime is greather then active_from validation_error = None for i, d in ((i, d) for i, d in enumerate(self.cleaned_data) if d): # don't bother with empty edit-inlines if not d: continue # both datetimes entered if d['active_from'] and d['active_till']: if d['active_from'] > d['active_till']: validation_error = ValidationError( _('Block active till must be greater than Block active from' )) self.forms[i]._errors[ 'active_till'] = validation_error.messages if validation_error: raise ValidationError( _('Invalid datetime interval. Block active till must be greater than Block active from' )) # dictionary of blocks with tuples (active from, active till) items = {} for i, d in ((i, d) for i, d in enumerate(self.cleaned_data) if d): if not items.has_key(d['name']): items[d['name']] = [(d['active_from'], d['active_till'])] else: items[d['name']].append((d['active_from'], d['active_till'])) # check that intervals are not in colision errors = [] error_message = 'Block active intervals are in colision on %s. Specified interval stops at %s and next interval started at %s.' for name, intervals in items.items(): if len(intervals) > 1: intervals.sort(self.cmp_by_till) for i in xrange(len(intervals) - 1): try: # exact covering allwoved (00:00:00 to 00:00:00) if intervals[i][1] > intervals[i + 1][0]: errors.append( error_message % (name, intervals[i][1], intervals[i + 1][0])) except TypeError: errors.append(error_message % (name, 'Infinite', intervals[i + 1][0])) if errors: raise ValidationError, errors return self.cleaned_data
def post(self, request, *args, **kwargs): self.object = None try: user = self.request.user except: return HttpResponseRedirect('/') data = request.POST.copy() subject = f"Имате нова заявка от {data.get('parent')}" message = ( f"Родител: {data.get('parent')}\n" f"Дете: {data.get('child')}\n" f"Училище: {data.get('school')}\n" f"Клас: {data.get('group')}\n" f"Период: {data.get('period_from')} - {data.get('period_to')}\n" f"Телефон за връзка: {data.get('phone')}\n" f"Поща: {user.email}\n" f"{data.get('extra')}\n") form = ApplicationForm(data) if not form.is_valid(): raise ValidationError('Неправилно попълнен телефонен номер.') # +359 works 0888 works, but 555555 doesn't if form.is_valid() and user.is_authenticated: form.save() send_mail(subject=subject, message=message, from_email=user.email, recipient_list=[settings.EMAIL_HOST_USER], fail_silently=False) # mail_admins(subject=subject, message=message) if admins have real mail return super().post(data, *args, **kwargs) return HttpResponseRedirect('/')
def clean(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if confirm_password and (password != confirm_password): self.add_error("confirm_password", ValidationError("两次密码不一致")) else: return self.cleaned_data
def clean(self, *args, **kwargs): data = super(ValidateImageFile, self).clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file._size > self.max_upload_size: raise ValidationError( _('Veuillez garder la taille du fichier sous {}. Taille de fichier actuelle {}' .format(filesizeformat(self.max_upload_size), filesizeformat(file._size)))) else: raise ValidationError(_('Type de fichier non supporté.')) except AttributeError: pass return data
def clean(self, value): if not value: value = 0 else: try: value = Decimal(str(value).replace(',', '.').replace('-', '')) except: raise ValidationError('Informe um numero decimal %s' % value) return value
def clean(self): """Checks that no two email addresses are the same.""" if any(self.errors): # Don't bother validating the formset unless each form is valid return emails = [] for i in range(0, self.total_form_count()): form = self.forms[i] email = form.cleaned_data['email'] if email in emails: raise ValidationError( "Forms in a set must have distinct email addresses.") emails.append(email)
def clean_code(self): """Clean the code field for validation after the user submits the form. Raises: ValidationError: Raise warning to user to select valid Commodity Code Returns: [str]: Str of user-selected code """ code = self.cleaned_data['code'] if Code.objects.filter(code=code).exists(): return code else: raise ValidationError(generic_error)
def form_valid(self, form): tags = form.cleaned_data['tags'] if len(tags) > 5: raise ValidationError('Możesz wprowadzić maksymalnie 5 tagów.') max_length_slug = Eureka._meta.get_field('slug').max_length slug = orig = slugify(form.instance.title)[0:max_length_slug] for x in itertools.count(1): if not Eureka.objects.filter(slug=slug).exists(): break slug = "%s-%d" % (orig[:max_length_slug - len(str(x)) - 1], x) form.instance.slug = slug form.instance.created_by = self.request.user form.instance.eurekaInstruction = EurekaInstruction.objects.create() form.instance.mask = DeleteMask.objects.create() return super(EurekaCreateView, self).form_valid(form)
def clean(self): cleaned_data = self.cleaned_data if cleaned_data.get("text") == "Raise non-field error": raise ValidationError("Non-field error.") return cleaned_data
def clean_ssl_port(self): ssl_port = self.cleaned_data['ssl_port'] if ssl_port > 65535: raise ValidationError("Maximum port number is 65545.") return ssl_port