質問

I have a django model defined with an IPAddressField:

class ExampleModel(models.Model):
    ip = models.IPAddressField('An IP Address')

For my API, I have defined a HyperlinkedModelSerializer for this model that operates in coordination with a ViewSet as excepted. However, when testing create actions against my API, I don't receive all the errors that I would typically expect a validated Django Form to return. Specifically, if I leave the 'ip' field empty, I receive an error as I would expect:

{'ip': [u'This field is required.']}

But, if I POST a request with an invalid ip address such as:

{'ip': '10.3.'}

I would expect serializer.errors to contain an error akin to what a Django Forms validator does, which is:

{'ip': [u'Enter a valid IPv4 address.']}

Any thoughts, suggestions, or clarifications on the matter? Am I blind to some obvious fact?

I heard Tom Christie appears if you say his name three times. Tom Christie, Tom Christie, Tom Christie.

役に立ちましたか?

解決

Further investigation shows that DRF has no IpAddressField, but django validators can be passed as args to serializer fields. As such, validating an IPV4 Address without adding one can be done as follows:

from django.core.validators import validate_ipv4_address
...
ip = serializers.CharField(validators=[validate_ipv4_address]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top