Search code examples
python-3.xdjangodjango-modelsdjango-viewsdjango-validation

django custom validators function?


I have a model named X which has a

STATUS_CHOICES = ( (STATUS_A, 'A'), (STATUS_B, 'B'), (STATUS_O, 'Other'), ) and the field name status = models.CharField(max_length=48, choices=STATUS_CHOICES)

here i am trying to write a custom validator to for a spreadsheet when uploaded to check for the value that should return only the STATUS_CHOICES and any other value it should return error how should i write ?

validators.py

from app.model import X
def validate_A_or_B(value):
    return value in dict(X.STATUS_CHOICES).values()

is this correct?


Solution

  • You can define custom validation for a field like this:

    validators.py:

    from your_view.models import X
    from django.core.exceptions import ValidationError
    
     def validate_status(value):
    
         if value not in dict(X.STATUS_CHOICES).values():
             raise ValidationError("your message")
         return value
    

    You can use it in your models field like this: models.CharField(max_length=48, choices=STATUS_CHOICES, validators = [validate_status]) don't forget to include from .validators import validate_status