I have a field named bar i need to write a validation function to validate this bar in django what conditions can i apply to this and how should my function be?
Note:Please dont share link of django validators
models.py
class Model:
bar = models.CharField('Bar', max_length=255, blank=True, null=True)
CodePudding user response:
You can define a function that will validate the value and raise a ValidationError [Django-doc] in case the condition is not valid, so:
from django.core.exceptions import ValidationError
def validate_bar(value):
if not some-condition:
raise ValidationError('Bar should satisfy a certain condition', code='some_code')
then you add this function to the validators of that field
class MyModel(models.Model):
bar = models.CharField('Bar', max_length=255, blank=True, null=True, validators=[validate_bar])
note that validators will only run in ModelForms, ModelAdmins, ModelSerializers, etc. Not by the Django ORM for performance reasons.
CodePudding user response:
def val(v):
if v is not None:
try:
if len(v) <= 255:
return True
except ValidationError:
return False
does this work ? with balnk = True ,null = True and max_length
