Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 £$(*£$(£@$&£($ in the title field, which is converted into a slug using Django slugify.

Because none of these characters can be converted, Django returns an error. My question is, what should I put in the form validation method to raise a forms.ValidationError when the user uses a title like this?

Thanks.

like image 826
user116170 Avatar asked Jun 02 '09 18:06

user116170


People also ask

How do I check if a form is valid in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is slug in Django?

What is SlugField in Django? It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. Let's assume our blog have a post with the title 'The Django book by Geeksforgeeks' with primary key id= 2.

What is validation error in Django?

A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields.


2 Answers

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 import validate_slug

slug = 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.validators import 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.

like image 69
Oli Avatar answered Oct 19 '22 12:10

Oli


SLUG_REGEX = re.compile('^[-\w]+$')
like image 35
Ben Avatar answered Oct 19 '22 11:10

Ben