Last active
August 29, 2015 14:07
-
-
Save yuheiomori/08d6b5645ebd70c00937 to your computer and use it in GitHub Desktop.
formsetで少なくとも1つは入力させるためのチェック
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
from django import forms | |
class PersonForm(forms.Form): | |
name = forms.CharField() | |
age = forms.IntegerField() | |
class AtLeastOneFormRequiredBaseFormSet(forms.formsets.BaseFormSet): | |
at_least_on_form_required_error = u"少なくとも1つは入力してください" | |
def clean(self): | |
if not getattr(self.forms[0], "cleaned_data"): | |
raise forms.ValidationError(self.at_least_on_form_required_error) | |
PersonFormSet = forms.formsets.formset_factory(PersonForm, | |
extra=2, | |
formset=AtLeastOneFormRequiredBaseFormSet) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
from django.test import TestCase | |
from .forms import PersonFormSet | |
class PersonFormSetTest(TestCase): | |
def test_at_least_one_form_required(self): | |
data = { | |
'form-TOTAL_FORMS': '2', | |
'form-INITIAL_FORMS': '2', | |
'form-MAX_NUM_FORMS': '', | |
'form-0-age': '', | |
'form-0-name': '', | |
'form-1-age': '', | |
'form-1-name': '', | |
} | |
f = PersonFormSet(data) | |
self.assertTrue(f.is_bound) | |
self.assertFalse(f.is_valid()) | |
self.assertEquals(f.non_form_errors()[0], f.at_least_on_form_required_error) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment