From c3fd7c66856f39b697de0647adbc8d7b59323360 Mon Sep 17 00:00:00 2001 From: David Jones Date: Mon, 20 May 2013 13:04:38 +0100 Subject: [PATCH] Updated SlugField to raise validation errors for invalid slugs --- rest_framework/fields.py | 18 ++++++++++++++++-- rest_framework/tests/fields.py | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index b5f99823a..5c2ac5280 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -389,11 +389,25 @@ class URLField(CharField): class SlugField(CharField): type_name = 'SlugField' - + form_field_class = forms.SlugField + + default_error_messages = { + 'invalid': _("Enter a valid 'slug' consisting of letters, numbers," + " underscores or hyphens."), + } + default_validators = [validators.validate_slug] + def __init__(self, *args, **kwargs): super(SlugField, self).__init__(*args, **kwargs) - + def __deepcopy__(self, memo): + result = copy.copy(self) + memo[id(self)] = result + #result.widget = copy.deepcopy(self.widget, memo) + result.validators = self.validators[:] + return result + + class ChoiceField(WritableField): type_name = 'ChoiceField' form_field_class = forms.ChoiceField diff --git a/rest_framework/tests/fields.py b/rest_framework/tests/fields.py index dad69975f..a31042069 100644 --- a/rest_framework/tests/fields.py +++ b/rest_framework/tests/fields.py @@ -769,6 +769,21 @@ class SlugFieldTests(TestCase): self.assertEqual(serializer.is_valid(), True) self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 20) + def test_invalid_slug(self): + """ + Make sure an invalid slug raises ValidationError + """ + class SlugFieldSerializer(serializers.ModelSerializer): + slug_field = serializers.SlugField(source='slug_field', max_length=20, required=True) + + class Meta: + model = self.SlugFieldModel + + s = SlugFieldSerializer(data={'slug_field': 'a b'}) + + self.assertEqual(s.is_valid(), False) + self.assertEqual(s.errors, {'slug_field': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]}) + class URLFieldTests(TestCase): """