Django表单不验证 [英] Django formset doesn't validate

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

问题描述

我正在尝试保存一个表单,但似乎绕过了is_valid()即使有必填字段。

I am trying to save a formset but it seems to be bypassing is_valid() even though there are required fields.

要测试这个,我有一个简单的形式:

To test this I have a simple form:

class AlbumForm(forms.Form):
  name = forms.CharField(required=True)

查看:

@login_required
def add_album(request, artist):
  artist = Artist.objects.get(slug__iexact=artist)
  AlbumFormSet = formset_factory(AlbumForm)
  if request.method == 'POST':
    formset = AlbumFormSet(request.POST, request.FILES)
    if formset.is_valid():
      return HttpResponse('worked')
  else:
    formset = AlbumFormSet()
  return render_to_response('submissions/addalbum.html', {
   'artist': artist,
   'formset': formset,
  }, context_instance=RequestContext(request))

模板:

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset.forms %}
  <ul class="addalbumlist">
    {% for field in form %}
     <li>
        {{ field.label_tag }}
        {{ field }}
        {{ field.errors }}
     </li>
    {% endfor %}
  </ul>
{% endfor %}
   <div class="inpwrap">
    <input type="button" value="add another">
    <input type="submit" value="add">
   </div>
</form>






最后发生的是我点击添加没有输入一个名字,然后HttpResponse('工作')被称为似乎假设它是一个有效的表单。


What ends up happening is I hit "add" without entering a name then HttpResponse('worked') get's called seemingly assuming it's a valid form.

我可能会在这里缺少一些东西,但我看不出有什么问题。我想要发生的是,就像任何其他形式,如果该字段需要吐出一个错误,如果它没有填写任何想法?

I might be missing something here, but I can't see what's wrong. What I want to happen is, just like any other form if the field is required to spit out an error if its not filled in. Any ideas?

推荐答案

嗯,我有这个完全相同的问题。问题是你正在使用一个formset!表单允许窗体中的所有字段为空。但是,如果您有2个字段,并且仅填写一个字段,那么将会识别所需的内容。这样做是因为formets是用于批量添加的,有时您不想在页面上填写所有额外的表单。真烦人您可以在这里查看我的解决方案

Heh, I was having this exact same problem. The problem is that you're using a formset!! Formsets allow all fields in a form to be blank. If, however, you have 2 fields, and fill out only one, then it will recognize your required stuffs. It does this because formsets are made for "bulk adding" and sometimes you don't want to fill out all the extra forms on a page. Really annoying; you can see my solution here.

这篇关于Django表单不验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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