+class StudentBaseFormSet(NonEmptyBaseFormSet):
+ def check_unique_emails(self):
+ from django.forms.util import ErrorList
+
+ emails = set()
+ for form in self.forms:
+ if not form.is_valid():
+ continue
+ if form.cleaned_data:
+ email = form.cleaned_data['email']
+ instance = getattr(self, 'instance', None)
+ if email in emails:
+ errors = form._errors.setdefault('email', ErrorList())
+ errors.append(u'Każdy zgłoszony uczeń powinien mieć własny adres email')
+ elif instance and Confirmation.objects.exclude(contact=instance).filter(email=email).exists():
+ errors = form._errors.setdefault('email', ErrorList())
+ errors.append(u'Uczeń z tym adresem już został zgłoszony w innym formularzu.')
+ else:
+ emails.add(email)
+
+ def clean(self):
+ super(StudentBaseFormSet, self).clean()
+ self.check_unique_emails()
+
+
+class StudentUpdateFormSet(StudentBaseFormSet):
+ takes_instance = True
+
+ def __init__(self, *args, **kwargs):
+ instance = kwargs.pop('instance', None)
+ super(StudentUpdateFormSet, self).__init__(*args, **kwargs)
+ self.instance = instance
+
+ def clean(self):
+ super(StudentUpdateFormSet, self).clean()
+ self.check_unique_emails()
+
+