如何禁止向 CharField 输入特定字符
我有一个模型,我想禁止在标题字段中输入特殊字符(+、-、/、% 等):
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
我可以在模型本身中完成此操作吗?或者我是否必须对 forms.py 做一些事情,以便用户无法发布标题中带有特殊字符的表单。我究竟怎样才能做到这一点?
I have a model in which I want to disallow the input of special characters(+,-,/,%, etc) in the title field:
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
Can I accomplish this in the model itself? Or do I have to do something with the forms.py so that users arent able to post a form with special chars in the title. How exactly can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
validators= 添加验证器…
参数[Django-doc] 并使用逆正则表达式:You can add a validator with the
validators=…
parameter [Django-doc] and work with an inverse regex: