Search code examples
pythondjangodjango-modelsdjango-validationdjango-4.0

Custom django validation function


i have written validaiton function for an attribute is it correct and how should i write for same attribute with blank = True and add_1 is required field any conditions to add

add_1 = models.CharField(max_length=255)
add_2 = models.CharField(max_length=255, blank=True)

Note: All validators must return True or False

validators.py

def validate_add_1(value):
    if value is not None:
        try:
            if len(value) <= 255:
                return True
        except ValidationError:
            return False

Solution

  • According to Model Reference, when you add the "blank=True" attribute to any model field, that that field becomes optional. If you want a field to be required, do not specify blank attribute as the default is blank=False.

    For validator, I'm not sure what you are trying to do, but you can try something like this:

    def validate_add_1(value):
        val_len = False if len(value) > 255 else True
        # Return True if value is not blank/null and length of value <= 255
        return True if val_len and (value and value != '') else False
    

    Edit

    To simplify the above code for you to understand:

    def validate_add_1(value):
    
        # If length of value > 255, return False, else check for blank = True
    
        if len(value) > 255:
            return False
        else:
    
            # If value is not blank, AND value is not an empty string.
            # This is for checking blank = True condition is satisfied.
    
            if value and value != '':
                return True
            else:
                return False