验证Django中的slug [英] Validating a slug in Django
问题描述
£$($£$ $ $($
在标题字段中,即由于没有这些字符可以被转换,Django会返回一个错误,因为Django slugify
我的问题是,当用户使用这样的标题时,应该如何在表单验证方法中引用 forms.ValidationError
?
谢谢。
这个问题是十几岁,所以在更新我的问题时,我应该解释一下至少点头过去,某些功能可能不存在。
现在最简单的处理方式的方式是使用 django.models.SlugField
,它将为您验证自己,并暗示此字段是一个索引。
如果您没有使用在一个模型上,你仍然可以钩住SlugField使用的相同的验证器:
from django.core.validators import validate_slug
slug = forms.CharField(...,validators = [validate_slug])
如果您只想做幕后检查或编写自己的验证器,可以使用类似的技巧来提取Django定义的一个有效的插件。这只是正确使用validate_slug的正则表达式:
from django.core.validators import slug_re
如果slug_re.match(...):
...
我不能想象它会改变,但是通过锁定Django的想法,你会确保一致性,如果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.
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.
这篇关于验证Django中的slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!