Skip to content

Instantly share code, notes, and snippets.

@philwo
Created December 15, 2011 00:23
Show Gist options
  • Save philwo/1479247 to your computer and use it in GitHub Desktop.
Save philwo/1479247 to your computer and use it in GitHub Desktop.
class DynamicFormValidation(Validation):
""" Validation class that allows dynamic form classes and initial data.
Initial data is only used to validate the form - it will not modify
the data that the user has posted. So form validation might pass,
but saving the model will fail.
"""
initial = {}
def __init__(self, **kwargs):
self.form_class = kwargs.get('form_class', None)
def get_initial(self):
return self.initial
def get_form_class(self):
""" Returns a Form class object.
"""
if self.form_class:
return self.form_class
else:
msg = ('You need to override get_form_class or pass a form_class '
'kwarg to DynamicFormValidation().')
raise ImproperlyConfigured(msg)
def get_form_kwargs(self, bundle):
kwargs = {
'initial': self.get_initial(),
'data': self.data,
'instance': bundle.obj
}
return kwargs
def get_form(self, form_class):
return form_class(**self.get_form_kwargs())
def is_valid(self, bundle, request=None):
self.data = bundle.data.copy()
self.request = request
form_class = self.get_form_class()
if self.data is None:
self.data = {}
form = form_class(**self.get_form_kwargs(bundle))
if form.is_valid():
return {}
return form.errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment