Skip to content

Instantly share code, notes, and snippets.

@FeroxTL
Last active September 20, 2015 15:45
Show Gist options
  • Save FeroxTL/03917147da6c77b68607 to your computer and use it in GitHub Desktop.
Save FeroxTL/03917147da6c77b68607 to your computer and use it in GitHub Desktop.
django CBV mutliple forms mixin
class MultipleFormxMixin(object):
form_classes = []
initials = {}
prefixes = {}
form_names = []
def get_forms(self, names=None):
names = names or self.form_names
if len(names) != len(self.form_classes):
raise Exception('Number of forms and names isn\'t the same')
return dict(zip(
names,
[form(**self.get_form_kwargs(form))
for form in self.form_classes]))
def get_initial(self, form):
try:
return self.initials[form].copy()
except KeyError:
return {}
def get_prefix(self, form):
try:
return self.prefixes[form]
except KeyError:
return None
def get_form_kwargs(self, form):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(form),
'prefix': self.get_prefix(form),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
def get_context_data(self, **kwargs):
context = super(MultipleFormxMixin, self).get_context_data(**kwargs)
for name, form in self.get_forms(self.form_names).items():
if name not in kwargs:
context[name] = form
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment