How to use validators in django

隐身守侯 提交于 2020-03-03 10:01:08

问题


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?


回答1:


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()

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



来源:https://stackoverflow.com/questions/60419516/how-to-use-validators-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!