Raise validation error for empty formset

568 views
Skip to first unread message

Martin Tiršel

unread,
Dec 14, 2011, 4:22:08 PM12/14/11
to Django users
Hi,

I have a formset where I need to raise ValidationError if all forms in
this formset are empty and submitted but I can not find any useful
informations. Any suggestions?

Thanks,
Martin

Tom Evans

unread,
Dec 15, 2011, 6:52:44 AM12/15/11
to django...@googlegroups.com

To control validation on a formset, add a BaseFormset class and define
a clean() method on it:

https://docs.djangoproject.com/en/1.3/topics/forms/formsets/#custom-formset-validation

To determine whether all the forms are empty, you have to consider the
initial forms (from existing data) and the extra forms (for new data).
If any of the initial forms are invalid or not marked for deletion,
then there is a non empty form. If any of the extra forms have
changed, there is a non empty form. Therefore, something like this
should suffice:

def clean(self):
for form in self.initial_forms:
if not form.is_valid() \
or not (self.can_delete and form.cleaned_data.get('DELETE')):
return
for form in self.extra_forms:
if form.has_changed():
return
raise forms.ValidationError("No initial or changed extra forms")

Cheers

Tom

Martin Tiršel

unread,
Dec 23, 2011, 3:29:58 AM12/23/11
to django...@googlegroups.com
Hi

On Thu, 15 Dec 2011 12:52:44 +0100, Tom Evans <teva...@googlemail.com>
wrote:

> On Wed, Dec 14, 2011 at 9:22 PM, Martin Tiršel <dja...@blackpage.eu>
> wrote:
>> Hi,
>>
>> I have a formset where I need to raise ValidationError if all forms in
>> this
>> formset are empty and submitted but I can not find any useful
>> informations.
>> Any suggestions?
>>
>
> To control validation on a formset, add a BaseFormset class and define
> a clean() method on it:
>
> https://docs.djangoproject.com/en/1.3/topics/forms/formsets/#custom-formset-validation
>

I know about clean method.

> To determine whether all the forms are empty, you have to consider the
> initial forms (from existing data) and the extra forms (for new data).
> If any of the initial forms are invalid or not marked for deletion,
> then there is a non empty form. If any of the extra forms have
> changed, there is a non empty form. Therefore, something like this
> should suffice:
>
> def clean(self):
> for form in self.initial_forms:
> if not form.is_valid() \
> or not (self.can_delete and form.cleaned_data.get('DELETE')):
> return
> for form in self.extra_forms:
> if form.has_changed():
> return
> raise forms.ValidationError("No initial or changed extra forms")
>
> Cheers
>
> Tom
>

Thanks, this is what I was looking for.

Martin

Reply all
Reply to author
Forward
0 new messages