为什么我的自定义验证没有被调用?

发布于 2024-11-15 16:03:22 字数 1588 浏览 3 评论 0原文

我有这个模型和模型形式:

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

我在视图中像这样使用它们:

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

这是我的模板:

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

问题是,我的验证从未被调用。我有 3 条评论,我可以立即添加,如果它们的文本字段为空,django 会说没问题。我什么地方做得不对?

编辑:带有验证器的变体:

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

我的验证器没有被调用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千纸鹤带着心事 2024-11-22 16:03:22

据我所知,模型不使用 clean_% 方法。您应该使用验证器

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

编辑:答案很简单:在表单集中,所有字段中没有数据的表单都会被忽略。这就是表单集有效的原因。空表单使用 empty_permissed 创建=正确。这意味着它们将通过验证。覆盖其中任何一个,你就会得到你想要的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文