gpt4 book ai didi

python - 如何在 django 中使用验证器

转载 作者:太空宇宙 更新时间:2023-11-03 19:41:04 26 4
gpt4 key购买 nike

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_subject(value):
if value.isalnum():
raise ValidationError(_('%(value)s is not valid. Please use alphanumneric characters as subject names'), params={'value': value},)
class Exam(models.Model):  #Exam can have many questions
subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject]) #make it to reject a string of length 0

def __str__(self):
return self.subject

我希望此代码在我键入以下内容时引发错误

from my_app.models import Exam
exam = Exam()
exam.subject = ""
exam.save()

为什么我没有收到错误?

最佳答案

当您 .save() 对象时,验证器不会运行,这主要是出于性能原因。您可以调用.full_clean() method [Django-doc]验证模型对象:

from my_app.models import Exam

exam = Exam()
exam.subject = ''
exam<b>.full_clean()</b>
exam.save()

ModelForm 还将清理模型对象,因此如果您通过 ModelForm 创建或更新模型,验证器将会运行。

关于python - 如何在 django 中使用验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60419516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com