What is the recommended approach for SlugField validation in Django REST framework? -
i'm building restful api using django rest framework. 1 of models looks bit this:
class zone(models.model): name = models.slugfield(max_length=50, unique=true) ... other fields
so have built serializer this:
class zoneserializer(serializers.modelserializer): class meta: model = zone fields = ('name', ... other fields)
when posting data create new zone, i'm not sure how validation responsible , how should take place automatically. i've tried following test cases:
- when
name
valid slug of 50 characters or less, validation succeeds. - when
name
valid slug of 50+ characters, validation fails appropriate error message. - when
name
invalid slug (e.g. "abc def"), validation succeeds , zone created invalid name.
digging code can see length of field validated django.core.validators.maxlengthvalidator
in run_validators
in rest_framework/fields.py
, validate_slug
not included in list of validators.
i know can add validate_name
method serializer this:
def validate_name(self, attrs, source): """ make sure slug field """ value = attrs[source] if not validators.validate_slug(value): raise serializers.validationerror("not slug") return attrs
but seems overkill. doing wrong here?
sounds there's valid pull request in there. :) validate_slug
should happen automatically.
best course of action:
- double check django slug form field behavior against rest framework serializer field behavior - different?
- raise ticket issue, noting you've determined (1).
- try write failing test case , submit pull request.
- update pr fix if possible.
- profit!!!11!!!! (well, name in credits, , nice warm feeling having contributed fix)
cheers,
tom
Comments
Post a Comment