Created
February 20, 2010 12:19
-
-
Save JunKikuchi/309659 to your computer and use it in GitHub Desktop.
save() で parent を指定できる djangoforms.ModelForm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
from google.appengine.ext.db.djangoforms import * | |
class ModelForm(djangoforms.ModelForm): | |
def save(self, commit=True, parent=None, key_name=None, **kw): | |
"""Save this form's cleaned data into a model instance. | |
Args: | |
commit: optional bool, default True; if true, the model instance | |
is also saved to the datastore. | |
Returns: | |
A model instance. If a model instance was already associated | |
with this form instance (either passed to the constructor with | |
instance=... or by a previous save() call), that same instance | |
is updated and returned; if no instance was associated yet, one | |
is created by this call. | |
Raises: | |
ValueError if the data couldn't be validated. | |
""" | |
if not self.is_bound: | |
raise ValueError('Cannot save an unbound form') | |
opts = self._meta | |
instance = self.instance | |
if instance is None: | |
fail_message = 'created' | |
else: | |
fail_message = 'updated' | |
if self.errors: | |
raise ValueError("The %s could not be %s because the data didn't " | |
'validate.' % (opts.model.kind(), fail_message)) | |
cleaned_data = self._cleaned_data() | |
converted_data = {} | |
propiter = itertools.chain( | |
opts.model.properties().iteritems(), | |
iter([('key_name', StringProperty(name='key_name'))]) | |
) | |
for name, prop in propiter: | |
value = cleaned_data.get(name) | |
if value is not None: | |
converted_data[name] = prop.make_value_from_form(value) | |
try: | |
if instance is None: | |
kw.update(converted_data) | |
instance = opts.model(parent=parent, key_name=key_name, **kw) | |
self.instance = instance | |
else: | |
for name, value in converted_data.iteritems(): | |
if name == 'key_name': | |
continue | |
setattr(instance, name, value) | |
except db.BadValueError, err: | |
raise ValueError('The %s could not be %s (%s)' % | |
(opts.model.kind(), fail_message, err)) | |
if commit: | |
instance.put() | |
return instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment