Reputation: 2879
I'm building a RESTful API using the Django REST framework. One of my models looks a bit like this:
class Zone(models.Model):
name = models.SlugField(max_length=50, unique=True)
... other fields
So I have built a serializer like this:
class ZoneSerializer(serializers.ModelSerializer):
class Meta:
model = Zone
fields = ('name', ... other fields)
When posting data to create a new zone, I'm not sure how much validation I am responsible for and how much should take place automatically. I've tried the following test cases:
name
is a valid slug of 50 characters or less, validation succeeds.name
is a valid slug of 50+ characters, validation fails with an appropriate error message.name
is an invalid slug (e.g. "abc def"), validation succeeds and a Zone is created with the invalid name.Digging into the code I can see that the length of a field is validated by django.core.validators.MaxLengthValidator
in run_validators
in rest_framework/fields.py
, but validate_slug
is not included in the list of validators.
I know that I can add a validate_name
method to my serializer like this:
def validate_name(self, attrs, source):
"""
Make sure this is a slug field
"""
value = attrs[source]
if not validators.validate_slug(value):
raise serializers.ValidationError("Not a slug")
return attrs
but this seems like overkill. Am I doing something wrong here?
Upvotes: 3
Views: 1310
Reputation: 33901
Sounds like there's a valid pull request in there. :) validate_slug
probably should happen automatically.
Best course of action:
Cheers,
Tom
Upvotes: 2