Why is my custom validation not being called?
I have this model and modelform:
class Comment(models.Model):
text = models.CharField(max_length=100)
def clean_text(self):
print "called Comment"
if len(self.text) <= 5:
raise ValidationError("must have 5 chars at least")
class CommentForm(ModelForm):
class Meta:
model = Comment
def clean_text(self):
print "called CommentForm"
if len(self.text) <= 5:
raise ValidationError("must have 5 chars at least")
And I'm using them like this in the view:
CommentFormSet = modelformset_factory(model=Comment,form=CommentForm,extra=3)
if request.method == "POST":
formset = CommentFormSet(request.POST)
if formset.is_valid():
print "VALID FORM"
else:
formset = CommentFormSet()
return render_to_response("first.html",{开发者_开发知识库"formset":formset},context_instance=RequestContext(request))
And this is my template:
<form action="first" method="post">
{% csrf_token %}
{% for dict in formset.errors %}
{% for error in dict.values %}
{{ error }}
{% endfor %}
{% endfor %}
<table>
{{ formset }}
</table>
<input type="submit" value="Create"/>
</form>
The thing is, my validation is never called. I have 3 comments which I can add at once, and if their text field is empty, django says it's no problem. What am I not doing right?
EDIT: The variant with validator:
def validate_min(val):
print "validator called"
if len(val) <= 5:
raise ValidationError("At least 5 characters should be provided")
class Comment(models.Model):
text = models.CharField(max_length=100,validators=[validate_min])
My validator is not being called.
As I know models don't use clean_% methods. You should use validator.
def validate_min_length(value):
if len(value) <= 5:
raise ValidationError("must have 5 chars at least")
class Comment(models.Model):
text = models.CharField(max_length=100, validators=[validate_min_length])
Edited: the answer is simple: in formset forms with no data in all fields are ignored. That's why formset is valid. Empty forms are created with empty_permitted=True
. Which means they will pass validation. Override either of these and you'll get what you want.
精彩评论