También puede hacerlo utilizando el modelo si conoce la validación se aplicará a todos los objetos de esta clase . Para usar el siguiente en el nivel de formulario, use clean_data. Aquí es un derecho muestra a partir de la documentación de Django usando ValidationError
:
class Article(models.Model):
status = models.CharField(max_length=75, blank=False, null=False)
pub_date = models.CharField(max_length=75, blank=False, null=False)
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError('Draft entries may not have a publication date.')
# Set the pub_date for published items if it hasn't been set already.
if self.status == 'published' and self.pub_date is None:
self.pub_date = datetime.date.today()
Referencia: Model Instance Clean, Django Validators
aquí es un ejemplo formas:
class SimpleForm(forms.ModelForm):
def clean(self):
cleaned_data = super(SimpleForm, self).clean() # Get the cleaned data from default clean, returns cleaned_data
field1 = cleaned_data.get("field1")
field2 = cleaned_data.get("field2"),
if not field1 and not field2:
raise forms.ValidationError('Please fill in both fields.')
return cleaned_data
Referencia: Form & Field Validation
Nota: Si haciendo esto por un plugin Django CMS, asegúrese de reemplazar el método limpio (auto) en la definición models.py para el plugin, en lugar de en forms.py. –