1

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)
1
  • what are you trying to do? bar has no semantic by itself Commented Jan 29, 2022 at 12:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer i know the above structure but i need that some condition with respect to above field what can be the conditions is what is not striking for me
@itriedit: well the some-condition should be a Python expression that works with the value. For example value is not None and value.startswith('foo').
-1
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

1 Comment

the validator should not return True or False, but raise a Validation error in case it is invalid. Furthermore Django will automatically validate the length of a string, so that validation is not necessary.l

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.