Created by dan on Friday 8th January, 2010 at 3:14 PM
Tags: Django, Python, Web development
A slug field is a field, which only accepts alphanumberic characters and underscores. When creating models in Django, a models.SlugField class exists, which validates against this rule. Quite frustratingly, however Django doesn't have a forms.SlugField class at the moment. It's time for drastic action!
If any of you have been slaving over this problem for a long time, you'll kick yourself when you see how easy it is to implement.
Instead of using a generic CharField, you need to use a RegexField (unless of course you're fussy, if so, I'm not helping you!). It takes the same parameters as a CharField, but an additional one, which is key to the success of this mission, 'regex'. The below example is a simple Django forms implementation of the models SlugField:
pk = forms.RegexField(label='Identifier', help_text='Can only consist of alphanumeric characters and underscores (_)', regex=r'^\w+$')
So there you have it, almost too easy to implement. The regular expression matches only slug characters from start to end. You can also add the required=False tag if you need to, and it'll work just fine.