Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

docs

  • Loading branch information...
commit ee7c2f6b5bb3fc4f0516180cd43b1e3aa734deb0 1 parent ed0d5db
@tuxcanfly tuxcanfly authored
Showing with 30 additions and 2 deletions.
  1. +26 −2 profiles/forms.py
  2. +4 −0 profiles/models.py
View
28 profiles/forms.py
@@ -8,6 +8,11 @@
class ContactForm(forms.ModelForm):
+ """
+ We have overriden init to take the nested email formset
+ as a parameter. This makes sure that each contact formset is related
+ to each email formset.
+ """
def __init__(self, *args, **kwargs):
self.formset = kwargs.pop('formset', None)
@@ -15,15 +20,21 @@ def __init__(self, *args, **kwargs):
class Meta:
model = Contact
- exclude = ["emails", ]
+ exclude = ["emails", ] # We don't need emails in the form anymore
class BaseContactFormSet(BaseModelFormSet):
"""
- Handles nested formsets
+ This base formset is resposible for handling the email formset
+ belonging to each contact formset
"""
def _construct_forms(self):
+ """
+ Create an email formset and pass it to the
+ contact form as a extra kwarg, also restrict
+ the queryset to related objects only
+ """
self.forms = []
for i in xrange(self.total_form_count()):
data = self.data or None
@@ -41,22 +52,35 @@ def _construct_forms(self):
self.forms.append(self._construct_form(i, **extra_kwargs))
def is_valid(self):
+ """
+ For the formset to be valid, each form in the nested
+ formset should also be valid
+ """
for form in self.forms:
if not form.formset.is_valid():
return False
return super(BaseContactFormSet, self).is_valid()
def save_formsets(self, instance, form):
+ """
+ Save the formset and attach the results to the instance
+ """
emails = form.formset.save()
instance.emails.add(*emails)
return instance
def save_new(self, form, commit=True):
+ """
+ Save formsets
+ """
instance = super(BaseContactFormSet, self).save_new(form, commit)
self.save_formsets(instance, form)
return instance
def save_existing(self, form, instance, commit=True):
+ """
+ Save formsets
+ """
instance = super(BaseContactFormSet, self).save_existing(form, commit)
self.save_formsets(instance, form)
return instance
View
4 profiles/models.py
@@ -2,6 +2,10 @@
# Create your models here.
+# We have two models related by m2m: Email and Contact.
+# We want users to be able to fill up multiple contacts
+# and mutliple emails for each contact
+
class Email(models.Model):
email = models.EmailField()

0 comments on commit ee7c2f6

Please sign in to comment.
Something went wrong with that request. Please try again.