如何在Django中使用验证器 [英] How to use validators in django

查看:41
本文介绍了如何在Django中使用验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

键入以下代码时,我希望此代码引发错误

I want this code to raise an error when I keyed the following

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

为什么我没有收到错误消息?

Why Iam not getting an error?

推荐答案

当您 .save()对象时,验证程序不会运行,这主要是为了性能原因.您可以调用 .full_clean() 方法[Django-doc] 来验证模型对象:

The validators do not run when you .save() an object, this is mainly done for performance reasons. You can call the .full_clean() method [Django-doc] to validate the model object:

from my_app.models import Exam

exam = Exam()
exam.subject = ''
exam.full_clean()
exam.save()

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

A ModelForm will also clean the model object, so the validators will run if you create or update a model through a ModelForm.

这篇关于如何在Django中使用验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆