diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 74b8563e2c..03e8994ee8 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -890,6 +890,13 @@ class SlugField(CharField): def get_internal_type(self): return "SlugField" + def formfield(self, **kwargs): + defaults = {'form_class': forms.RegexField, 'regex': r'^[a-zA-Z0-9_-]+$', + 'error_messages': {'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.")}, + } + defaults.update(kwargs) + return super(SlugField, self).formfield(**defaults) + class SmallIntegerField(IntegerField): def get_manipulator_field_objs(self): return [oldforms.SmallIntegerField] diff --git a/docs/modelforms.txt b/docs/modelforms.txt index 1be7c3a882..b9495e0acd 100644 --- a/docs/modelforms.txt +++ b/docs/modelforms.txt @@ -65,7 +65,8 @@ the full list of conversions: (from ``django.contrib.localflavor.us``) ``PositiveIntegerField`` ``IntegerField`` ``PositiveSmallIntegerField`` ``IntegerField`` - ``SlugField`` ``CharField`` + ``SlugField`` ``RegexField`` accepting only letters, + numbers, underscores and hyphens ``SmallIntegerField`` ``IntegerField`` ``TextField`` ``CharField`` with ``widget=Textarea`` ``TimeField`` ``TimeField`` diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index c7e726ee4e..da45f23f74 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -301,11 +301,11 @@ u'third-test' [, , ] If you call save() with invalid data, you'll get a ValueError. ->>> f = CategoryForm({'name': '', 'slug': '', 'url': 'foo'}) +>>> f = CategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) >>> f.errors['name'] [u'This field is required.'] >>> f.errors['slug'] -[u'This field is required.'] +[u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] >>> f.cleaned_data Traceback (most recent call last): ...