Bullet check in Django

I guess this will include regex or something like that, but I will give it a chance. At this point, the user can break down the website by entering something similar to £$(*£$(£@$&£($ in the header field, which is converted to a pool using Django slugify .

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

Thanks.

+6
python django validation slug
source share
2 answers

This question has been around for half a decade, therefore, updating my question, I must explain that I at least nod to the past, where some functions may be missing.

The easiest way to handle bullets in forms these days is to simply use django.models.SlugField . It will check itself for you and implies that this field is an index.

If you are not using this on a model, you can still use 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 an off-screen check or write your own validator, you can use a similar method to pull out the definition of a valid Django pool. This is just a compiled regex that uses validate_slug above:

 from django.core.validators import slug_re if slug_re.match(...): ... 

I can’t imagine that this will change, but if you stick to Django’s slime idea, you’ll ensure consistency if Django changes one day.

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

All Articles