问题
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