David Jones - iPushPull
David Jones - iPushPull

Reputation: 2879

What is the recommended approach for SlugField validation in Django REST framework?

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:

  1. When name is a valid slug of 50 characters or less, validation succeeds.
  2. When name is a valid slug of 50+ characters, validation fails with an appropriate error message.
  3. When 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

Answers (1)

Tom Christie
Tom Christie

Reputation: 33901

Sounds like there's a valid pull request in there. :) validate_slug probably should happen automatically.

Best course of action:

  1. Double check the Django slug form field behavior against the REST framework serializer field behavior - are they definitely different?
  2. Raise a ticket for the issue, noting what you've determined from (1).
  3. Try to write a failing test case and submit it as a pull request.
  4. Update the PR with the fix if possible.
  5. Profit!!!11!!!! (Well, get your name in the credits, and get a nice warm feeling for having contributed the fix)

Cheers,

Tom

Upvotes: 2

Related Questions