Search code examples
pythonpython-3.xdjangodjango-rest-frameworkdjango-serializer

Which field can be used in django serializers for entering ipaddress with subnet mask


Which field can be used in django serializers for entering ipaddress with subnet mask. example: x.x.x.x\x is the input format.


Solution

  • If you using marshmallow, you can create own field type

        from marshmallow import fields, validate
    
    class IpField(fields.String):
        def __init__(self, *args, **kwargs):
            kwargs['validate'] = validate.Regexp(r'(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)',
                                                 error='Not valid IP')
            super().__init__(*args, **kwargs)
    

    And if you use from rest_framework import serializers

    serializers.RegexField(regex='(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)')