Skip to content

Instantly share code, notes, and snippets.

@justinfay
Created June 19, 2013 09:10
Show Gist options
  • Save justinfay/5812881 to your computer and use it in GitHub Desktop.
Save justinfay/5812881 to your computer and use it in GitHub Desktop.
>>> class PopulableForm(forms.Form):
... def populate(self, other):
... for k, v in self.cleaned_data.items():
... if hasattr(other, k):
... setattr(other, k, v)
... else:
... try:
... other[k] = v
... except TypeError:
... continue
...
>>> class FooForm(PopulableForm):
... a = forms.CharField()
... b = forms.CharField()
...
>>>
>>> f = FooForm({'a':1,'b':2})
>>> f.is_valid()
True
>>> d = {}
>>> f.populate(d)
>>> d
{'a': u'1', 'b': u'2'}
>>> class FooObject(object):
... def __init__(self):
... self.a = None
... self.b = None
...
>>>
>>> foo_ob = FooObject()
>>> foo_ob.a
>>> foo_ob.b
>>> f.populate(foo_ob)
>>> foo_ob.b
u'2'
>>> foo_ob.a
u'1'
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment