我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用django.forms.forms.ValidationError()。
def clean(self, value): if value: # Si se reciben valores (id's de Tpvs), cargarlos para comprobar si son todos del mismo tipo. # Construimos un ValuesQuerySet con sólo el campo "type", hacemos la cuenta y ordenamos en orden descendente para comprobar el primero (esto es como hacer un "group_by" y un count) # Si el primero es mayor que 1 mostramos el error oportuno. count = models.VPOS.objects.filter(id__in=value).values("type").annotate(Count("type")).order_by( "-type__count") if count[0]["type__count"] > 1: raise forms.ValidationError("Asegúrese de no seleccionar más de un TPV del tipo '{0}'".format( dict(models.VPOS_TYPES)[count[0]["type"]])) return super(VPOSField, self).clean(value)
def validate_url(data, query): """ Checks if the given url contains the specified query. Used for custom url validation in the ModelForms :param data: full url :param query: string to search within the url :return: """ if data and query not in data: raise forms.ValidationError('Please enter a valid {} url'.format(query))
def clean(self, *args, **kwargs): data = super(SizeAndContentTypeRestrictedImageField, 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 forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size))) else: raise forms.ValidationError(_('Filetype not supported.')) except AttributeError: pass return data
def clean(self, *args, **kwargs): data = super(ContentTypeRestrictedFileField, 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 forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size))) else: raise forms.ValidationError(_('Filetype not supported.')) except AttributeError: pass return data
def test_invalid_key_data(self): form = KeyForm(data={ 'key': "The cat in the hat didn't come back after that", 'use_asc': False, }) self.assertFalse(form.is_valid()) form.cleaned_data = form.data with self.assertRaises(forms.ValidationError): form.clean_key()