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"))
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(HardJsonFormField, self).clean(value) except TypeError: raise ValidationError("فرمت json صحیحی نیست")
def clean(self): cleaned_data = super(AddSamplesForm, self).clean() if cleaned_data["substrate"] == "custom" and not cleaned_data.get( "substrate_comments"): self.add_error( "substrate_comments", ValidationError(_( "For a custom substrate, you must give substrate comments." ), code="required")) if cleaned_data.get("rename") == "cleaning" and not cleaned_data.get( "cleaning_number"): self.add_error( "cleaning_number", ValidationError(_( "You must provide a cleaning number if you want to use it for the names." ), code="required")) return cleaned_data
def clean(self, value): if not value and not self.required: return None if not value.startswith(u"1") and not value.startswith(u"3"): raise ValidationError(self.error_messages['invalid']) value = value.strip() if "\n" in value: raise ValidationError(u"Multiple lines in the bitcoin address") if " " in value: raise ValidationError(u"Spaces in the bitcoin address") if re.match(r"[a-zA-Z1-9]{27,35}$", value) is None: raise ValidationError(self.error_messages['invalid']) version = get_bcaddress_version(value) if version is None: raise ValidationError(self.error_messages['invalid']) return value
def save(self, commit=True): product = super().save(commit=False) if self.request.user.owner_of is None: raise ValidationError( "Product doesn't have independent existence,create Restaurent First " ) product.restaurent_id = self.request.user.owner_of if commit: product.save() return product
def _clean_category(self, category_pk): # Check category in allowed ones try: category = self._categories.get(id=category_pk) except Category.DoesNotExist as e: raise ValidationError( self.error_messages['categorynotallowed'], code='categorynotallowed', ) from e return category
def from_db_value(self, value, expression, connection): ''' https://docs.djangoproject.com/en/2.0/howto/custom-model-fields/#converting-values-to-python-objects https://github.com/dmkoch/django-jsonfield/issues/214 ''' if isinstance(value, six.string_types) and value: try: return json.loads(value, **self.load_kwargs) except ValueError: raise ValidationError(_("Enter valid JSON")) return value
def to_python(self, value): if isinstance(value, six.string_types): if not value.strip(): return '' try: return json.loads(value, **self.load_kwargs) except ValueError: raise ValidationError(_("Enter valid JSON")) return value
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): super().clean() has_one_correct_answer = False for form in self.forms: if not form.cleaned_data.get('DELETE', False): if form.cleaned_data.get('is_correct', False): has_one_correct_answer = True break if not has_one_correct_answer: raise ValidationError('Mark at least one answer as correct.', code='no_correct_answer')
def clean(self): cleaned_data = super(SubstrateForm, self).clean() if cleaned_data.get( "material") == "custom" and not cleaned_data.get("comments"): self.add_error( "comments", ValidationError(_( "For a custom substrate, you must give substrate comments." ), code="required")) return cleaned_data
def clean(self): """check the form submitted with new password""" cleaned_data = self.cleaned_data if cleaned_data.get('password') and cleaned_data.get('password_check'): if not cleaned_data.get('password') == \ cleaned_data.get('password_check'): raise ValidationError(_("Password doesn't match.")) # TODO: check that password is strong enough ? return cleaned_data
def _clean_cell( self, data, constraint: GraphHandCellConstraint) -> Optional[EntityCell]: clean_value = self.clean_value required = self.required cell_info = clean_value( data, self.cell_data_name, dict, required, 'ecellrequired', ) if not cell_info: raise ValidationError( self.error_messages['ecellrequired'], code='ecellrequired', ) cell_key = clean_value( cell_info, self.cell_key_data_name, str, required, 'ecellrequired', ) if not cell_key: return None cell = constraint.get_cell( cell_key=cell_key, not_hiddable_cell_keys=self.not_hiddable_cell_keys, ) if cell is None: raise ValidationError( self.error_messages['ecellnotallowed'], code='ecellnotallowed', ) return cell
def clean(self): """check passwords""" cleaned_data = self.cleaned_data if cleaned_data.get('new_password1') and \ cleaned_data.get('new_password2'): if not cleaned_data.get('new_password1') == \ cleaned_data.get('new_password2'): raise ValidationError(_("Password doesn't match.")) # TODO: check that password is strong enough ? return cleaned_data
def clean_from_sample(self): from_sample = self.cleaned_data["from_sample"] if from_sample and (from_sample.split_origin or models.SampleSplit.objects.filter( parent=from_sample).exists() or models.SampleDeath.objects.filter( samples=from_sample).exists()): raise ValidationError(_( "It is not possible to merge a sample that was split, killed, or is the result of a sample split." ), code="invalid") return from_sample
def validate_email_nouser(email): """ Check if the email address does not belong to an existing user. """ # Check whether we should be subscribed to as a user User = get_user_model() if User.objects.filter(email__exact=email).exists(): raise ValidationError( _("The e-mail address '%(email)s' belongs to a user with an " "account on this site. Please log in as that user " "and try again.") % {'email': email})
def to_python(self, value): if not value: return None elif isinstance(value, (int, long)): return timeutils.TimeDeltaWrapper(microseconds=value * 1000) elif isinstance(value, basestring): milliseconds = timeutils.parse_to_millisec(value) return timeutils.TimeDeltaWrapper(microseconds=milliseconds * 1000) elif isinstance(value, (datetime.timedelta, timeutils.TimeDeltaWrapper)): return value raise ValidationError('Unable to convert %s to timedelta.' % value)
def clean(self, value): if self.required and not value: raise ValidationError(self.error_messages['required']) elif not self.required and not value: return [] if not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['list']) final_values = [] # if there is only one lookup used to limit choices, then a real # validation over that limited choices is performed lookups_list = utils.getLookups(self.lookups) limit_choices_to = {} if len(lookups_list) != 1 else lookups_list[0][1] for val in value: try: obj = self.model.objects.get(pk=val, **limit_choices_to) except self.model.DoesNotExist: raise ValidationError(self.error_messages['invalid_choice'] % val) else: final_values.append(obj) return final_values
def clean(self, value): if not value and not self.required: return None built = {} value = super(EnvironmentFormField, self).clean(value) kv_pairs = [v.strip() for v in value.split('\n') if v.strip()] for kv in kv_pairs: split = kv.split('=', 1) if len(split) != 2: raise ValidationError('Please enter valid key-value pairs.') built[split[0].strip()] = split[1].strip() return built
def clean(self): cleaned_data = super(TaskForm, self).clean() if cleaned_data.get("status") in [ "2 accepted", "3 in progress", "0 finished" ]: if not cleaned_data.get("operator"): self.add_error( "operator", ValidationError( _("With this status, you must set an operator."), code="required")) return cleaned_data
def clean(self): cleaned_data = super(SubstrateForm, self).clean() if "material" in cleaned_data and "comments" in cleaned_data: if cleaned_data[ "material"] == "custom" and not cleaned_data["comments"]: self.add_error( "comments", ValidationError(_( "For a custom substrate, you must give substrate comments." ), code="invalid")) return cleaned_data
def clean_password_2(self): get_data = self.cleaned_data.get password1 = get_data('password_1') password2 = get_data('password_2') if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2
def clean(self): if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return staffings = [] for form in self.forms: if form.cleaned_data.get("detail_type", "") != "TIME_SPENT_MISSION": continue staffing = [form.cleaned_data['mission'].id, form.cleaned_data['month'].toordinal(), form.cleaned_data["consultant"].id] if staffing in staffings: raise ValidationError(_("Cannot declare twice the same consultant for the same mission on a given month")) staffings.append(staffing)
def clean(self): cleaned_data = super(DepositionForm, self).clean() if "number" in cleaned_data and "timestamp" in cleaned_data: if cleaned_data["number"][:2] != cleaned_data[ "timestamp"].strftime("%y"): self.add_error( "number", ValidationError(_( "The first two digits must match the year of the deposition." ), code="invalid")) return cleaned_data
def clean_password_2(self): data = self.data pw2 = data['password_2'] if data['password_1'] != pw2: raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(pw2, self.user2edit) return pw2
def validate_editable_entity(entity, user, code='changenotallowed'): validate_authenticated_user( user, ugettext_lazy( u'Not authenticated user is not allowed to edit entities'), code) try: user.has_perm_to_change_or_die(entity) except PermissionDenied as e: raise ValidationError(str(e), code=code) from e return entity
def clean(self): super().clean() has_one_correct_answer = False for form in self.forms: if not form.cleaned_data.get("DELETE", False): if form.cleaned_data.get("is_correct", False): has_one_correct_answer = True break if not has_one_correct_answer: raise ValidationError("mark atleast one correct answer", code="no_correct_answer")
def clean_email(self): """check e-mail submitted in the database""" email = self.cleaned_data['email'] try: Email.objects.get(email=email) except Email.DoesNotExist: raise ValidationError( _('This should be the email address\ registered for your AIn7 account.')) else: return self.cleaned_data['email']
def clean(self): cleaned_data = super(EditTopicForm, self).clean() if "members" in cleaned_data and "confidential" in cleaned_data: if cleaned_data["confidential"] and \ not any(permissions.has_permission_to_edit_topic(user, self.topic) for user in cleaned_data["members"]): self.add_error( "members", ValidationError(_( "In confidential topics, at least one member must have permission to edit the topic." ), code="invalid")) return cleaned_data
def clean_email_field(self): data = self.cleaned_data['email_field'] if not data: raise ValidationError(_("An e-mail address is required.")) # Check whether we should be subscribed to as a user User = get_user_model() try: user = User.objects.get(email__exact=data) raise ValidationError(_( "The e-mail address '%(email)s' belongs to a user with an " "account on this site. Please log in as that user " "and try again." ) % {'email': user.email}) except User.DoesNotExist: pass # Check whether we have already been subscribed to try: subscription = Subscription.objects.get( email_field__exact=data, newsletter=self.instance.newsletter ) if subscription.subscribed and not subscription.unsubscribed: raise ValidationError( _("Your e-mail address has already been subscribed to.") ) else: self.instance = subscription self.instance = subscription except Subscription.DoesNotExist: pass return data