Skip to content Skip to sidebar Skip to footer

Validating A Slug In Django

I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to £$(*£$(£@$&£($

Solution 1:

This question is half a decade old so in updating my question I should explain that I'm at least nodding to the past where some features might not have existed.

The easiest way to handle slugs in forms these days is to just use django.models.SlugField. It will validate itself for you and imply that this field is an index.

If you're not using this on a model, you can still hook in the same validator that SlugField uses:

from django.core.validators importvalidate_slugslug= forms.CharField(..., validators=[validate_slug])

If you just want to do behind-the-scenes checking or write your own validator, you can use a similar technique to pull in Django's definition of a valid slug. It's just the compiled regex that validate_slug above uses:

from django.core.validatorsimport slug_re

if slug_re.match(...):
    ...

I can't imagine it will change, but by locking yourself to Django's idea of a slug, you'll ensure consistency if Django does change one day.

Solution 2:

SLUG_REGEX = re.compile('^[-\w]+$')

Post a Comment for "Validating A Slug In Django"