[Django]-Django rest framework & model validation

3👍

This works for me:

class ZipCodeValidator(RegexValidator):
    regex = r'^[0-9]{5}$'
    message = 'Invalid ZipCode.'


class MyModel(models.Model):
    zipcode = models.CharField(max_length=5, blank=True, validators=[ZipCodeValidator()])


class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel


>>> s1 = MyModelSerializer(data={'zipcode': '34234'})
>>> s1.is_valid()
True
>>> s2 = MyModelSerializer(data={'zipcode': 'f3434'})
>>> s2.is_valid()
False
>>> s2.errors
{'zipcode': [u'Invalid ZipCode.']}

2👍

Actually, I think the first solution you proposed @astrognocci, even if it seems quite verbous, is a good solution for Django REST Framekork v3.0 +,

Indeed, .full_clean() method is not called anymore in ModelSerializer validation process, as explained in this post

So writing custom class validators – that can be used in Model and ModelSerializer – seems a relevant option for DRY concerns, and consistence.

Leave a comment