Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django formset doesn't validate

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)

The view:

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

And the template:

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

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?

like image 999
tsoporan Avatar asked Mar 16 '10 04:03

tsoporan


1 Answers

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.

like image 102
mpen Avatar answered Sep 22 '22 01:09

mpen